Gustavo Amgarten
Gustavo Amgarten

Reputation: 396

jQuery Ajax request with error 404 (not found) but it works

I'm sending a jQuery AJAX request to the server, but the browser's console tells me that the page is not found. Still, my Spring MVC signature mapping the requested URL is executed, and yet the done part of the AJAX function is not.

Here is the relevant code:

Javascript:

    var content = $(data).filter("#wrapper-email-content");
    $.ajax({
        url : '/sendEmail',
        type : 'POST',
        data : {
            content: content.html()
        }
    }).done(function(){
        console.log("Finished")
    });

Spring MVC Signature:

@RequestMapping(value = "/sendEmail", method = RequestMethod.POST)
public void sendEmail(
    HttpServletRequest request, String content) {

    UserTO user = (UserTO) request.getSession().getAttribute("USER");
    String email = user.getEmail();
    String title = "Your order";
    Email.sendEmail(title, email, content, null, null, null);
}

So, in the code, the email is sent, meaning that sendEmail method is executed, but I still get the Error 404: not found from the AJAX request, and "Finished" is not printed in the console.

What am I doing wrong?

Upvotes: 4

Views: 8211

Answers (3)

deadconversations
deadconversations

Reputation: 1937

EDIT: see solution posted for What to return if Spring MVC controller method doesn't return value?

Not familiar with MVC Spring, but you probably need to return a success status code yourself:

public String sendEmail(
    HttpServletRequest request, @RequestBody String content) {

    UserTO user = (UserTO) request.getSession().getAttribute("USER");
    String email = user.getEmail();
    String title = "Your order";
    Email.sendEmail(title, email, content, null, null, null);
    return new ResponseEntity<String>(json,HttpStatus.OK);
}

Upvotes: 1

Selim Ok
Selim Ok

Reputation: 1161

The better solution is annotating your method with

@ResponseStatus(value = HttpStatus.OK)

see answer https://stackoverflow.com/a/12839817/954602 for the example.

Upvotes: 1

Karthika
Karthika

Reputation: 110

@RequestMapping(value = "/sendEmail",headers="Accept=application/json", method = RequestMethod.POST)
public Map<String,String> sendEmail(
    HttpServletRequest request, @RequestBody String content) {
    Map<String,String> statusMap=new HashMap<String,String>();
    UserTO user = (UserTO) request.getSession().getAttribute("USER");
    String email = user.getEmail();
    String title = "Your order";
    Email.sendEmail(title, email, content, null, null, null);
    statusMap.put("status","Mail sent successfully");
    return statusMap;
}

Upvotes: 2

Related Questions