AJcodez
AJcodez

Reputation: 34166

jQuery AJAX calls error callback on 202 response- shouldn't that be a success callback?

Well its all in the title. I'm trying to check the user's password before performing destructive actions:

$.ajax({
  type: 'POST',
  url: '/path/to/post.json',
  data: { password: '**********' },
  success: function() { console.log("Success!"); },
  error: function() { console.log("Error!"); }
});

In console:

202 Accepted 123ms
Error!

I thought 403 Forbidden for wrong password and 202 Accepted for correct password would be appropriate response codes, but I don't know much about HTTP to be honest.

jQuery version 1.8.3

Upvotes: 10

Views: 6383

Answers (2)

Esailija
Esailija

Reputation: 140230

The error callback is not fired due to the status of 202 but due to an error in parsing the response as JSON. For jQuery, 2xx and 304 is a success.

If the response body is Invalid Password that's invalid json and triggers the jQuery error when it tries to parse it. A proper JSON string has quotes around it, like "Invalid Password". You should JSON encode your responses using a JSON serializer, not construct json manually which you can see is error-prone.

Upvotes: 14

AJcodez
AJcodez

Reputation: 34166

Nevermind, got it working with

statusCode: {
  202: function() { console.log("Success!"); },
  403: function() { console.log("Error!'); }
}

Instead of success and error callbacks. Still a little baffling 202 triggers the error one though.

Upvotes: 1

Related Questions