1

How can I get some javascript to run before a document ready function?

I have the following snippet finished first...

var applicantlist = [];
$.getJSON("apps.json", function(appsdata) {
    for (var i = 0; i<appsdata.applications.length; i++){
        var tempapp = [appsdata.applications[i].name, appsdata.applications[i].server];
        applicantlist.push(tempapp);
    }
});

I've tested this, and the data gets pushed into the array just fine. The problem is that I need this array to make some ajax calls that are found in my page ready function as follows...

$(document).ready(function(){
    window.jsonpCallbacks = {};
    alert(applicantlist.length);
    for (var i = 0; i < applicantlist.length; i++){
        (function(index){
            window.jsonpCallbacks["myCallback" + index] = function(data){
                myCallback(data,index);
            };
        })(i);
        //Jquery/Ajax call to the WoW API for the data.
        $.ajax({
            "url":"http://us.battle.net/api/wow/character/" + applicantlist[i][1] + "/" + applicantlist[i][0] + "?jsonp=jsonpCallbacks.myCallback" + i,
            "type":"GET",
            "data": { fields: "items, talents, progression, professions, audit, guild, stats"},
            "dataType":"jsonp",
            "contentType":"application/json",
            "jsonpCallback":"jsonpCallbacks.myCallback"+i,
            "success":function(data1){
            }
        })

    }

All of this fires off before the first snipet, no matter where I seem to put it. So, the array is empty (the alert message just shows "0").

As you can see by the URL of my ajax call, I need that array populated beforehand. I've tried putting the first snippet in a seperate .js file and calling it before all other javascript files on the actual HTML page...

What am I missing?

5
  • 2
    Running it before document.ready won't help. It's still asynchronous, and won't set the variable until after document.ready. Anything that depends on the result of AJAX has to be done in its callback function. Commented Mar 16, 2014 at 20:32
  • nothing here depends on Ajax, Ajax depends on the array. Commented Mar 16, 2014 at 20:51
  • You're filling in the array with $.getJSON, that's AJAX. Commented Mar 16, 2014 at 20:52
  • I see what you mean, sorry. So I'll figure out a new way to do this. Commented Mar 16, 2014 at 20:54
  • I didn't realize this is what was happening to me until I saw your question listed in the google search results. Just by chance, I clicked on it and read the question and what do you know, this IS what I was running into. Thank you for the well worded question. :) Commented Sep 24, 2017 at 15:10

1 Answer 1

2

Move the code that sends the first request to the document.ready. You don't usually want anything happening before the document is ready. Then move the code that sends the next request(s) to the callback of the first request after you populate the array and do whatever else you need to happen first

$(document).ready(function () {
    $.getJSON("apps.json", function(appsdata) {
        ...
        // add items to your array
        sendNextRequest();
    }
});

function sendNextRequest() {
    //Jquery/Ajax call to the WoW API for the data.
    ...
}

This gurantees that the calls to the WoW api don't get fired until the first $.getJSON call completes and you populate your array.

FYI this is a common challenge in javascript. You need one operation to run only after another finishes. When you use ajax, you have callbacks like in my example above that help you achieve this. Outside of ajax requests, you can use jQuery Promises to defer tasks until after something else finishes.

Sign up to request clarification or add additional context in comments.

1 Comment

When I have the one array, this works perfectly. However, if I have two ajax calls, then this isn't working for both arrays, just the one. Do you have a suggestion for this scenario? Realistically there will be more than just two that need populating...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.