Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.getScript: data variable in callback undefined

Tags:

jquery

ajax

I'm trying to load an external JavaScript using jQuery's getScript(), like this:

$.getScript("http://api.recaptcha.net/js/recaptcha_ajax.js", function(data) {
    window.alert(data);
});

but as the alert window shows, the data variable in the callback function is undefined, unlike promised in http://docs.jquery.com/Ajax/jQuery.getScript#urlcallback.

Anyone know why this might be?

Thanks.

like image 236
Hannes Avatar asked Jul 08 '09 07:07

Hannes


2 Answers

If you look at the source to getScript (line 3338 in jQuery-1.3.2.js), you can see that the documentation is wrong here. The data parameter is for sending data to the server in the query string, which jQuery assumes you won't need for loading scripts; it's used in, for instance, getJSON. getScript just hardcodes data to null, and automatically evaluates the retrieved script for you.

So the bad news is that the documentation is wrong. The good news is that you probably just wanted to evaluate the script anyway, so you probably don't even need the callback at all.

like image 139
C Pirate Avatar answered Sep 30 '22 09:09

C Pirate


Yes it is loading the script but strangely the data variable is undefined. But i tried accessing the variable (RecaptchaStr_en) from the script from remote site and it is defined.

$.getScript("http://api.recaptcha.net/js/recaptcha_ajax.js", function(data) {
        window.alert(data);
        alert($(RecaptchaStr_en));
    });
like image 42
TheVillageIdiot Avatar answered Sep 30 '22 07:09

TheVillageIdiot