user1335163
user1335163

Reputation: 131

Jquery ajax call will not reach succes function

Pulling out my hair. Countless hours trying to get ajax call to work...

Jquery:

function doAjaxPost(episode_id) {

    alert("cc");
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/yay/episodes/remove",
        data: JSON.stringify({
            episode_id : episode_id
        }), 
        dataType: 'json',
        contentType: "application/json",
        success: function(){

            alert("o");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.error(errorThrown);
        }
    });
}; 

Controller:

    @RequestMapping(value = "/episodes/remove", method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.OK)
    public void removeEpisodeFromList(@RequestBody String episode_id) {

        System.out.println("Episode_id : " + episode_id);       
    }

And I call the function from:

<a href = "#" onclick = "doAjaxPost(${episode.episode_pk});"> MARK AS WATCHED </a>

It reaches the controller where the correct thing is printed out. But then FireBug just says "SyntaxError {}" and success function alert is never called.

Upvotes: 0

Views: 902

Answers (1)

benashby
benashby

Reputation: 468

It probably won't affect the data being passed in, but you really don't need the JSON.stringify action on your data parameter. See http://api.jquery.com/jQuery.ajax/#example-0

Also, if you are trying to get JSON back from your spring MVC controller, you need to use the @ResponseBody annotation. This will instruct Spring to not try to render out the template. I actually wrote a blog post about getting JSON back from a spring MVC application a little while back that may help.

The section titled "Mapping the response body with the @ResponseBody annotation" here can give you more information

Also, the success() function is depreciated. The done() function should be used now. More information on that can be seen at the jquery url above.

Hope this helps!

http://benashby.com/spring/response-body-annotation

Upvotes: 1

Related Questions