Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle ajax 201

When making a ajax call see example below success does gets a 201 status retuned. How do you handle these better i.e. 200, 201 within the success function?

$.ajax({
    type: "POST",
    dataType: "json",
    url: "http://api.domain.com/sms",
    data: {
      // Send value in mobile input field.
      mobile: $("#mobile").val(),
    },
    // On successful AJAX call do the following.
    success: function(data) {
      $('#messageText').text('SMS successfully sent');
    },
    error: function(jqXhr) {
      data = JSON.parse(jqXhr.responseText);
    }
});
like image 487
Prometheus Avatar asked Sep 13 '12 15:09

Prometheus


People also ask

How do you handle AJAX failure?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.

How do I respond to AJAX JSON?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.


2 Answers

This is an old question but I'd like to comment anyway.

I had the same problem and one thing that solved it for me was leaving the "dataType" unsetted. When you do this jQuery will try to guess the data type the server is returning and will not throw an error when your server returns a 201 with no content.

Hope it helps.

like image 56
Herberth Amaral Avatar answered Oct 11 '22 13:10

Herberth Amaral


Use the statusCode object:

var handle200 = function(data, textStatus, jqXHR) {
    alert('200'); // success codes have the success signature
};

var handle201 = function(data, textStatus, jqXHR) {
    alert('201'); // success codes have the success signature
    // test it if you are in doubt:
    console.log(data);
    console.log(textStatus);
    console.log(jqXHR);
};

var handle404 = function(jqXHR, textStatus, errorThrown) {
    alert('404'); // failing codes have the error signature
});

var request = $.ajax({
    type: 'POST',
    url: '/myresource/posttarget',
    data: { name: 'john' },
    statusCode: {
        200: handle200,
        201: handle201,
        404: handle404
    }
});
like image 39
acdcjunior Avatar answered Oct 11 '22 12:10

acdcjunior