Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 694
AJcodez Avatar asked Mar 14 '13 16:03

AJcodez


People also ask

Why does ajax call fail?

ajax method lets you set a timeout in milli seconds. When a timeout happens, The fail callback is called, with errorThrown set to "timeout". The request is aborted, meaning that even if the response arrives later on, your done callback is not called by jQuery.

Is ajax successful deprecated?

Yes, it is deprecated in jQuery 1.8 onwards. You should use . done() and use . fail() to catch the errors.

What is ajax callback?

The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.

Does ajax wait for response?

ajax() function with the default settings, any JavaScript code after this AJAX request will be executed without waiting for a response. In most cases, this is the desired behavior, but there are some situations where you will want to prevent further execution until there has been a response to the AJAX call.


1 Answers

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.

like image 113
Esailija Avatar answered Sep 28 '22 21:09

Esailija