Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery ajax done callback not responding to 201

I have an ajax post as such:

$.post("/api/v1/payment_methods/create_credit_card", values)
.done (response) ->
  console.log("GOOD JOB")
.fail (response) ->
  console.log("Adas")

The response is a 201, however, done doesn't seem to be capturing it and instead it's going to fail. I thought 201 would of been considered a success and would of been captured by done. Any ideas of why it wouldn't be working?

Note: The above code is in coffeescript, which doesn't really affect the question but explains my syntax

like image 289
JustNeph Avatar asked Feb 20 '13 19:02

JustNeph


2 Answers

Looking at the source, success should fire for anything between 200 - 300 and 304. An alternative is to explicitly call out the statusCode:

$.ajax({
  statusCode: {
    201: function() {
      console.log("HERE");
    }
  }
});
like image 125
Keith Rousseau Avatar answered Oct 16 '22 12:10

Keith Rousseau


So we figured out what was wrong, JSON.parse was throwing a Syntax Error - so the values sent in isnt in a valid JSON format. The poster wasnt able to see the Syntax error in chrome, but firebug showed the error.

This indicates that whenever Javascript will throw an exception, the response might still be 200, 201, 202 etc. - but because of the syntax error the fail() function would be triggered.

EDIT - Also you should probably use a different response, many use 200 - OK, but Id recommend to use 202 - ACCEPTED in this case.

like image 8
am_ Avatar answered Oct 16 '22 14:10

am_