13

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

5 Answers 5

18

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

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.

1
  • Thanks it helped. I sent a JSON content instead cause I can manage the server.
    – KeitelDOG
    Commented Aug 9, 2019 at 0:19
3

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.

0

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

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.