Handling HTTP status Ajax response

2.4k views Asked by At

I am attempting to integrate the Instapaper Simple API into something but I am struggling to understand how to handle the response that the API sends back in Javascript. The article is adding to Instapaper just fine so I know that the submission is working just not my response handlers.

This is the code I have so far and I'm guessing that the success function is not the correct way of handling the response.

$.ajax({
    type: 'GET',
    url: url,
    dataType: 'jsonp',
    success: function( data, status ) {
        alert("yay");
    },

    error: function(status) {
        alert("oh noes");
    }
});
return false;

Instapaper returns a 201 when the article has been added. I can see that in the Google Chrome Network tool that the GET returned a 201 status. Just wondering how I handle that status within the code above.

Thanks.

Edit When I click the link to activate the code below it pops up the alter under the error function right now even though it has worked.

2

There are 2 answers

4
ioseb On BEST ANSWER

jQuery.ajax() provides statusCode map for such purposes:

$.ajax({
    type: 'GET',
    url: url,
    dataType: 'jsonp',
    statusCode: {
      200: function( data ) {
          alert("yay");
      },
      201: function( data ) {

      }
    },
    error: function(status) {
        alert("oh noes");
    }
});

http://api.jquery.com/jQuery.ajax/

0
Jarry On
$.ajax({
  statusCode: {
    201: function() {
      alert("201!");
    }
  }
});

this should work with any http status code