Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors in jQuery.getScript

jQuery's getScript function doesn't seem to support an error callback function. I can't use the global ajax error handling code here, a local error function would be ideal.

Documentation that the callback gets data/textStatus seems incorrect - the callback gets neither.

Any suggestions on how I detect that a call to getScript failed (server not available, for instance)?

EDIT: Just looked at source, and it seems like the callback is only invoked on success, with data always set to null and textStatus not defined (since it's a success-only callback, I presume). The documentation is very incorrect for this function.

like image 846
psychotik Avatar asked Sep 10 '09 17:09

psychotik


4 Answers

As of jQuery 1.5 you can append a .fail to your call to getScript.

$.getScript('foo.js', function(){
    //script loaded and parsed
}).fail(function(){
    if(arguments[0].readyState==0){
        //script failed to load
    }else{
        //script loaded but failed to parse
        alert(arguments[2].toString());
    }
})

http://api.jquery.com/jQuery.getScript/#handling-errors

like image 96
som Avatar answered Nov 20 '22 16:11

som


For cross domain script tags, the success event fires but the error event does not; no matter what syntax you use. You can try this approach:

  1. Create an error handler and set it to fire after few seconds using handle = window.setTimeout
  2. Inside your success callback function, cancel the timeout using window.clearTimeout(handle)

Sample code:

var timeoutId; // timeout id is a global variable
timeoutId = window.setTimeout(function() {
    alert("Error");
}, 5000);
$.getScript("http://other-domain.com/script.js", function(){
    window.clearTimeout(timeoutId);
});
like image 17
Salman A Avatar answered Nov 20 '22 16:11

Salman A


The global JQuery Ajax-ErrorHandler will work!

Prior to the $.getScript-Call setup the Error Handler to cach the error.

$(document).ajaxError(function(e, xhr, settings, exception) {
    alert('error in: ' + settings.url + ' \n'+'error:\n' + exception );
});

As described in the JQuery manual: http://api.jquery.com/ajaxError/.

like image 8
DrMabuse Avatar answered Nov 20 '22 15:11

DrMabuse


jquery.ajax has a alternative way to handle error

jQuery.ajax({
        type: "GET",
        url: 'http://www.example.com/script_test.js',
        dataType: "script",
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('error ', errorThrown);
        },
        success:function(){
            console.log('success');
        }
    });
like image 4
Amadu Bah Avatar answered Nov 20 '22 14:11

Amadu Bah