I'm sending a form value to Controller to load more data from database by ajax call in Springboot project. but getting 404 xhr failed error(I'm using Spring security also).
I've attached Controller, Script and error log
@GetMapping("/company_selection")
public String showCompanies(Model model, @AuthenticationPrincipal CustomUserDetails user) {
model.addAttribute("pageTitle","Select Company");
model.addAttribute("companies",companyService.listCompanies(user.getId()));
model.addAttribute("CompanySelectCriteria", new CompanySelectCriteria());
Map<Long, String> years = new TreeMap<>();
model.addAttribute("years", years);
return "company_select";
}
@PostMapping(value = "/company_selection", produces = MediaType.APPLICATION_JSON_VALUE , consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Map<Long, String> showYears(Model model, @RequestBody YearCriteria yearCriteria) {
Map<Long, String> years = companyService.listYears(yearCriteria.getCompanyName());
return years;
}
JQuery Ajax
<script type="text/javascript">
$(document).ready(function() {
$("#companies").change(function() {
var company = $(this).find(":selected").val();
var json = {
"companyName" : company
};
$.ajax({
type : "POST",
contentType : "application/json",
url : "/company_selection",
data : JSON.stringify(json),
dataType : 'json',
cache : false,
timeout : 600000,
success : function(data) {
var html = '';
html += '<option value="0"></option>';
for (let elem of data.entries()) {
html += '<option value="' + '${elem[0]}' + '">'
+ '${elem[1]}'
+ '</option>';
}
html += '</option>';
$('#year_id').html(html);
},
error : function(e) {
alert(e);
}
});
});
});
</script>
Usually web applications use default context path for all controllers. It specified by property server.servlet.context-path=path
. Check default value for it or specify your own, and use path like that: /path/company_selection