AJAX does not work with 404 .... but does it work? What gives?

Perhaps I should just close my mouth and move forward, but something tells me that everything is not working as well as I think, and I need to fix it.

Basically, I make a simple AJAX call to tell the server what the user has chosen: an existing project or a new project. AJAX is as follows:

var dataString = 'existingProject='+ $("#existingProject").val() + '&newProjName=' + $("#newProjName").val(); //AJAX call to post selections to server $.post('/myproj/manageProjects.html',dataString); 

The Spring MVC signature that handles this post call looks like this:

 @RequestMapping(value="/manageProjects",produces="application/json",method=RequestMethod.POST) public StatusResponse manageProjects( @RequestParam(value="existingProject",required=false) String existingProj, @RequestParam(value="newProjName",required=false) String newProj, HttpSession session){ 

What blows my mind, I get a call in manageProjects with the correct variables and values ​​that I expect. The server processes the request and returns the pojo I created, called StatusResponse, which wraps a boolean (success or failure) and a list of server feedback messages. I create one with a simple β€œtrue” status for success and pass it back.

The client then issues 404 manageProjects.html, which was not found and continues its fun journey as if nothing had happened.

So ... found it or not? If a pojo like StatusResponse is an inappropriate response from Spring MVC, what is the correct answer? Why did the message successfully get to the controller, but then the client received 404 ?!

Thanks for any insight ....

Footnote: Apologies if this sounds like an earlier question from today. I came to the main problem due to the wrong angle and created more confusion than necessary in this post ...

+4
source share
2 answers

When this happened to me, it usually happens because there is a form in dom, and you press the submit button, which launches xhr. It launches xhr, but it also submits the form, which will be the default for the current URL if none are specified. So try stopping the javascript event from spreading, remove submit, or just remove the form tag.

+2
source

Try adding the @ResponseBody annotation, something like

 @RequestMapping(value="/deleteUser/{id}", method = RequestMethod.POST) public @ResponseBody ResponseEntity<String> deleteUser(@PathVariable("id") long id) { ... return new ResponseEntity<String>(HttpStatus.OK); } 
+1
source

Source: https://habr.com/ru/post/1402780/


All Articles