Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax does not parse json on failure

Tags:

jquery

jQuery's jqXHR object passed to the callback on failure does not parse json responses, therefore responseJSON is undefined only responseText is available.

It works fine for successful requests, I am setting the correct headers using dataType: 'json'

Call:

  $.ajax({
    type: 'POST',
    url: $form.attr('action'),
    data: post_data,
    dataType: 'json',
    done: done_callback,
    fail: fail_callback,
    always: always_callback
  });

Request Headers:

Accept:application/json, text/javascript, */*; q=0.01
X-Requested-With:XMLHttpRequest
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11

Response Headers:

Content-Type:application/json;charset=utf-8
Status:500

responseText:

{"status":"error","code":500,"message":"A system error occurred, please try again later"}

responseJSON is undefined

Is it the case that jQuery does not parse json when the response to ajax requests is unsuccessful? I cannot find any documentation to confirm or deny this behaviour (I could be just not looking hard enough)

I can obviously just use parseJSON in the fail callback.

like image 713
Rob Avatar asked Mar 22 '12 11:03

Rob


1 Answers

I had a look into the jQuery ajax callback method. It does the dataType conversion only if ( status >= 200 && status < 300 || status === 304 ) is true; otherwise the response is passed, as such, to the corresponding handler. That is, if the request is a failure then the response is not parsed as per the expected dataType.

If you want more info you can look for the above condition in the jquery.js file and see it working.

like image 128
Arun P Johny Avatar answered Oct 11 '22 12:10

Arun P Johny