41

I need some suggestions here or maybe some explanations. I have a jquery ajax call,

$.ajax({
 type: "GET",
 url: base_url+'/ajax/fetch/counts/',
 dataType: 'json',
 data: {},
 error: function(xhr, error){
        console.debug(xhr); console.debug(error);
 },
 success: display_counts
});

It's working fine. My success callback fires correctly with response. But, what I noticed is that my error callback is fired every time, even when my call returns success status 200. In the above error callback, I see that object xhr.status is 200.

Can anybody explain what's wrong, or what is happening here? error callback is supposed to fire only when I have 404 or maybe a non-200 response. Are my assumptions correct?

Thanks.

6 Answers 6

39

Just an suggestion, try using the $.ajaxSetup() to get the correct error like this:

$(function() {
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Just as an aside, the Docs state: Note: Global callback functions should be set with their respective global Ajax event handler methods—.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()—rather than within the options object for $.ajaxSetup(). so it would seem that this would be better used in .ajaxError()
So an important thing to realize of course is that your ajax could fail on a user's computer if their internet connection is spotty. So your app could be working fine but they get failed ajax requests because of a bad internet connection - which appears to be identifiable by the status === 0 and exception === 'timeout' cases above.
Also note that docs state that: "This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API."
36

Error callback is called on http errors, but also if JSON parsing on the response fails. This is what's probably happening if response code is 200 but you still are thrown to error callback.

2 Comments

If you are expecting a non JSON response. You can set the dataType option to script/text...etc Checkout api.jquery.com/jQuery.ajax and look under dataFilter for more information.
I was calling a cgi script, I needed it to dump out the data in json format. It was returning a string which failed.
2

A recent question had similar problem with json jquery requests, try removing surrounding () from your json response.

3 Comments

Funny, I've had a similar problem that was fixed by adding surrounding brackets.
@Coronatus Yes, this what I usually used to do, but jquery 1.4.2 starts to rely on browser's JSON.parse, my firefox's JSON.parse would parse {"key":"value"} successfully, but issue an error on ({"key":"value"}).
To get around the differences in which browsers parse JSON, I would recommend using Douglas Crockford's parser: json.org/json2.js
2

A few things I can think of:

  1. Make sure you have disabled caching by setting cache: false.
  2. If you are using Firefox, try using Firebug and the Net tab to monitor the request
  3. Don't rely on the browser's JSON parser. I would recommend this one: https://github.com/douglascrockford/JSON-js/blob/master/json2.js from the creator of JSON no less

4 Comments

"trivial and obvious" - well, that was simply harsh. :)
Well sorry if that was really harsh. +1 already for referring to JSON parser thing. :)
@SimpleCoder "Don't rely on the browser's JSON parser"?? why? is it the same for now??
@mfadel: Some older browsers don't support JSON, so using a third-party parser in the first-place could prevent compatibility headaches.
1

I'm not a jQuery expert, but I know that bwith Prototype.js, the AJAX error handler fires if the request is successful but the success handler causes an an error. Is that the same in jQuery? You could test if this is what's happening by putting the entire contents of display_counts in a try..catch block.

Comments

-1

Change dataType from plain/text to html

1 Comment

...but OP doesn't even have plain/text dataType

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.