Reputation: 1559
I'm sending a query to a server and awaiting a JSON object in return:
var a = $.ajax(
{
type: "POST",
data: post_data,
timeout: 5000,
url: url,
beforeSend: function (xhr)
{
xhr.setRequestHeader("Content-Type", "application/json");
}
})
.success (function (data, status, jqxhr)
{
onSuccess();
})
.error (function(x, status, jqxhr)
{
onError_(x);
});
That works perfectly, I'm getting the expected JSON in return:
{"readyState":4,"responseText":"","status":201,"statusText":"Created"}
But not onSuccess()
but onError_()
gets called and status
is set to 'parsererror'
despite the return is a valid JSON (I've tested it with various tools like this) and even the status of the JSON element is 201
which according to this page represents a positive status code:
10.2.2 201 Created
The request has been fulfilled and resulted in a new resource being created [...]
Is it possible, that jQuery's Ajax interprets the 201 status as a failure?
Update:
Also adding dataType: "json",
to my request doesnt change the situation. The jQuery documentation for .ajax()
says
dataType (default: Intelligent Guess (xml, json, script, or html))
So when I implemented it I thought jQuery wouldn't be so dumb to cause errors because it doesn't recognize JSON and it seems that I was right because the error remains the same.
Update:
The common fix for this problem seems to be, adding dataType: "json"
to the ajax call, however this didn't work for me, so I did an ugly but working workaround:
.error (function(x, status, jqxhr)
{
if (x.status == 201) /* jQuery thinks, Status 201 means error, but it doesnt so we have to work around it here */
{
// handle success
return;
}
// handle errors
}
Anyway, I'd be still interested in a proper fix
Upvotes: 1
Views: 4848
Reputation: 2263
Be careful: ResponseText is equal to "" and that is not a valid json. It should be null or "{}"
Upvotes: 4