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);
    }
});

Answers:

Answer

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
    }
});
Answer

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.

Answer

Data inserted successful but jquery still returning error

The answer here appears to be a work around you can use for now. However, if you're using cross-domain, AJAX has some issues with that. Check out this SOF thread on it:

Problems Reading the HTTP Status/Error Code from jQuery AJAX

Answer

We had a similar problem; Looking at the jquery 1.9 source, a 201 status code expects content. If there is no content (or of the wrong content type) returned with the 201, then the fail callback is invoked.

Answer

Instead of

ResponseEntity<?> responseEntity = new ResponseEntity<>(HttpStatus.CREATED);

I used

ResponseEntity<?> responseEntity = new ResponseEntity<>(detailVO, HttpStatus.CREATED);

Where detailVO is my object to rutrun in case of success. Then in browser I got response in success function.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.