kramer65
kramer65

Reputation: 54013

Why does an empty 200 create a fail in jQuery?

I've created a simple ajax request to post some json to my api. I've done this a couple times before in other pages, but suddenly I can't get this new call to work properly.

var request = $.ajax({
    type: "POST",
    url: "/my-api-call",
    dataType: "json",
    data: JSON.stringify({"pid": 5, "comment": $('#comment').val()})
});
request.done(function(data){
    console.log('weve got a succesful response!!');
})
request.fail(function(error){
    console.log('weve got an error!!!');
    console.log(error);
});

The call simply returns an empty 200 response, which I verify in the browser. But somehow the browser console constantly says weve got an error!!!. As you can see I also log the error, but I that is an object so full of information, that I have no idea what could be important in it. In that error object it also says the response is a plain 200 btw.

Seeing that this code is fairly simple, I can't really figure out what I'm doing wrong.

Does anybody know what I'm doing wrong here? All tips are welcome!

Upvotes: 1

Views: 534

Answers (1)

Liam
Liam

Reputation: 29760

It's because you've set your dataType to json. So jquery is trying to parse your data (which is empty) to json. An empty result is not valid json.

"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

From the docs

so you should return {} or null

Upvotes: 4

Related Questions