Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you synchronously load a script from another directory via an ajax call?

I often need to load other javascript files via ajax, so at the beginning I used the standard function jQuery provides for script loading:

$.getScript('script_name.js',callback_function());

But this didn't work out, since $.getScript is asynchronous (the jQuery API for $.ajax says 'async' is set to true by default; topic is discussed in the comments of the API for $.getScript: http://api.jquery.com/jQuery.getScript/). So I wrote this function, as provided by someone in the comments of the API page linked above:

load:function(script,callback){

    jQuery.ajax({

        async:false,

        type:'GET',

        url:script,

        data:null,

        success:callback,

        dataType:'script'

    });

},

This seemed to work well, so I went on, but I recently noticed, that this only works for scripts in the same directory, eg. calling myObj.load('test.js') works well, but calling myObj.load('test/test.js') doesn't work at all.

It feels like I'm missing something obvious, but I didn't manage to find the problem. Any idea?

like image 697
Alex Avatar asked Dec 27 '10 15:12

Alex


People also ask

How do you make AJAX call synchronously?

Synchronous AJAX call is made when async setting of jQuery AJAX function is set to false while Asynchronous AJAX call is made when async setting of jQuery AJAX function is set to true. Default value of the async setting of jQuery AJAX function is true.

Can AJAX be made synchronous?

AJAX can access the server both synchronously and asynchronously: Synchronously, in which the script stops and waits for the server to send back a reply before continuing. Asynchronously, in which the script allows the page to continue to be processed and handles the reply if and when it arrives.

What is synchronous request in AJAX?

What is Synchronous Ajax? Synchronous Ajax request is the process in which execution of the request stops until a response is received and Asynchronous Ajax request means the script continue the process without waiting for the server to reply. It will handle the reply if it arrives.

Is an AJAX call synchronous or asynchronous?

Ajax requests are Asynchronous by nature, but it can be set to Synchronous , thus, having the codes before it, execute first.


2 Answers

Update: See the comment stream below, it's nothing to do with jQuery, it's a file permissions problem on the server.


Original answer:

Do you get any errors from the browser? For instance, in Chrome or Safari, if you open the Dev Tools and look at the Console tab, does it show errors? Or in Firefox, install Firebug and check in Firebug's console. Or in IE, use the free version of VS.Net... Something should be complaining to you about something.

You can also get more information from your code itself by supplying an error function rather than assuming success:

jQuery.ajax({
    async:false,
    type:'GET',
    url:script,
    data:null,
    success:callback,
    dataType:'script',
    error: function(xhr, textStatus, errorThrown) {
        // Look at the `textStatus` and/or `errorThrown` properties.
    }
});

Update: You've said you see textStatus = 'error' and errorThrown = undefined. Very strange. Does the same script work if you move it so it's not on a subpath? I wonder if the subpath is a red herring, and the real problem is a syntax error in the script.


Off-topic: Does it really have to be synchronous? You can't just poll for a symbol to appear? It's just that synchronous ajax requests really trash the user experience. In many browsers, not just your own page but all pages lock up during the request.

Here's what I mean by polling: Suppose I wanted to load jQuery asynchronously from JavaScript:

function loadScript(url, symbol, callback) {
    var script, expire;

    // Already there?
    if (window[symbol]) {
        setTimeout(function() {
            callback('already loaded');
        }, 0);
    }

    // Determine when to give up
    expire = new Date().getTime() + 20000; // 20 seconds

    // Load the script
    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    document.body.appendChild(script);

    // Start looking for the symbol to appear, yielding as
    // briefly as the browser will let us.
    setTimeout(lookForSymbol, 0);

    // Our symbol-checking function
    function lookForSymbol() {
        if (window[symbol]) {
            // There's the symbol, we're done
            callback('success');
        }
        else if (new Date().getTime() > expire) {
            // Timed out, tell the callback
            callback('timeout');
        }
        else {
            // Schedule the next check
            setTimeout(lookForSymbol, 100);
        }
    }
}

Usage:

// Load jQuery:
loadScript("path/to/jquery.min.js", "jQuery", function(result) {
    // Look at 'result'
});
like image 135
T.J. Crowder Avatar answered Sep 21 '22 05:09

T.J. Crowder


You can set ajax calls to be synchronous by default using ajaxSetup. This is how it looks like:

$.ajaxSetup({async:false});
$.getScript('script_name.js', callback_function);

If you need asynchronous calls again, just enable it with:

$.ajaxSetup({async:true});
like image 41
Benny Neugebauer Avatar answered Sep 19 '22 05:09

Benny Neugebauer