Get AJAX data from server before document ready (jQuery)

Smit picture Smit · May 10, 2013 · Viewed 9.1k times · Source

I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.

$(document).ready(function () {
    UseAjaxQueryForFillGlobalArray();
    MakingInterfaceUsingGlobalArray();       
});

But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.

If I do like this:

UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {     
    MakingInterfaceUsingGlobalArray();       
});

Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.

How to fix it? Maybe I using totally incorrect way?

Added after comments:

This is my ajax function:

function UseAjaxQueryForFillGlobalArray(){
    var curUserId = '<%= Master.CurrentUserDetails.Id %>';
    var curLocale = '<%= Master.CurrentLocale %>';
    $.ajax({
        type: "POST",
        url: "/segment.aspx/GetArrayForCF",
        data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            //here is I doing parse my string from server and fill arrays.     
        }
    });
}

Answer

Nicola Peluchetti picture Nicola Peluchetti · May 10, 2013

I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only

function UseAjaxQueryForFillGlobalArray() {
    // make the call
    $.post(url, data, function() {
        // let's be sure that the dom is ready
        $(document).ready(function () {    
            // use the array
            MakingInterfaceUsingGlobalArray();      
        }
    }
}();// invoke the function