Zain Shaikh
Zain Shaikh

Reputation: 6043

Why jQuery does not raise error event when an ajax call fails

Why jQuery does not raise any error event when I execute following script?

thought I have registered the error event, but it is not fired.

chrome shows me following error in Network tab in Console.

GET http://www.google.com/adfdaf?callback=jQuery15204572567550931126_1321347602706&_=1321348668347 404 (Not Found)

javascript:

    $.ajax({
        type: "GET",
        url: 'http://google.com/adfdaf?callback=?',
        dataType: "jsonp",
        success: function (msg) {
            console.log('Custom Domain validated successfully.');
        },
        error: function () {
            console.log('Error occured while validating Custom Domain.');
        }
    });

Upvotes: 3

Views: 1036

Answers (3)

James Allardice
James Allardice

Reputation: 165971

The jQuery docs for .ajax state the following:

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

You can use .getJSON instead. For example:

$.getJSON("url?callback=?", function() {
    //Success!
}).error(function() {
    //Error!
});

Edit

Looks like that won't work either. It seems the workaround is to supply a timeout option to .ajax:

$.ajax({
    type: "GET",
    url: 'http://google.com/adfdaf?callback=?',
    dataType: "jsonp",
    timeout: 5000,
    success: function (msg) {
        console.log('Custom Domain validated successfully.');
    },
    error: function () {
        console.log('Error occured while validating Custom Domain.');
    }
});

Obviously, that's not ideal, but the error handler will run after 5 seconds.

Upvotes: 5

Andrew Stubbs
Andrew Stubbs

Reputation: 4462

From the documenation:

Note: This handler is not called for cross-domain script and JSONP requests

I could be screwing up my terminology but I assume by requesting from google that makes this a cross-domain request.

Upvotes: 0

Related Questions