Pablo Pablo - 1 year ago 50
Ajax Question

Promise callback on Jquery never runs when empty response

I have a POST service in backend which returns an empty response body.

I call the service with an ajax call from jquery like this which returns a promise:

return $.when($.ajax({
type: 'POST',
url: url,
beforeSend: (xhr) => {
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
data: data,
dataType: 'json',
crossDomain: true

Then calling the method:

(response) => {

So the ajax call is made, however, the done is never runned.
If the server returns something in the response body it works.

Not sure what am I missing.

Answer Source

Jquery 1.9 treats json ajax requests with an empty result as a failure.

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 for more information on proper JSON formatting.)

You should either handle this as a fail case, not use the json type, or fix your server to not send empty responses when json is requested.