John Smith
John Smith

Reputation: 1105

How to handle a 204 response in jquery ajax?

As I have declared success and error ajax options, where the response is 204, the ajax method goes to option success which leads to an error.

As per the documentation we can use, StatusCode or Complete methods but the disadvantage here is have to declare all the status code like 2?? series, 3?? series, 4?? series! As these response are dynamic and I am not sure about the http status code.

So, which is better way to handle http status code in jquery ajax?

Upvotes: 19

Views: 21629

Answers (2)

aorfevre
aorfevre

Reputation: 5064

The solution above is a nice solution but for someone who already defines "success" and "error" on many components, this involves a lot of changes of code.

After a reading on the documentation, it is rather easy to get status code on success too :

jQuery.ajax({
..
'success' : function(data,textStatus,jqXHR) {
    if (jqXHR.status == "204") {

    }
},
error : function(jqXHR, exception) {
        // Manage error 
    },

http://api.jquery.com/jquery.ajax/ => statusCode

Then to check status code, a jqXHR.status will do the trick

Upvotes: 12

Scott Puleo
Scott Puleo

Reputation: 3684

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface. The third argument in the done function is a jqXHR object. This object has a property for the http status code of the result.

jqXHR.done(function(data, textStatus, jqXHR) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details. link

    $.ajax({
      url: "http://fiddle.jshell.net/favicon.png",
      beforeSend: function ( xhr ) {
          xhr.overrideMimeType("text/plain; charset=x-user-defined"); 
      }
    }).done(function ( data, textStatus, jqXHR) {
       console.log(jqXHR.status); //handle your 204 or other status codes here
    });

Fiddle http://jsfiddle.net/puleos/fVa7X/

Assuming you want to treat all non 200 status codes as an error you could do something like this:

var p = $.ajax({
          url: "http://fiddle.jshell.net/favicon.png",
          beforeSend: function ( xhr ) {
             xhr.overrideMimeType("text/plain; charset=x-user-defined"); 
          }
        });

p.done(function(data, textStatus, jqXHR) {
  if(jqXHR.status !== 200) {
     handleError(jqXHR.status);
     return;
  }
  // Normal processing here
});

p.fail(function(jqXHR, textStatus) {
   handleError(jqXHR.status); 
});

Upvotes: 19

Related Questions