1

This gives me the content of a file, in an alert box. As long as the alert is inside the get-functions block it's working fine:

var allActivities = [];

$(document).ready(function() {
    $.get('./activities.txt', function(result) {
        currentActivity = result.split(",");
        allActivities.push(currentActivity);
        alert(allActivities); // Alert box returns correct results
    });
}

But when I move the alert outside of the get-function scope, the alert box is empty. I'm guessing I have messed up with some scopes, but I can't figure out what.

var allActivities = [];

$(document).ready(function() {
    $.get('./activities.txt', function(result) {
        currentActivity = result.split(",");
        allActivities.push(currentActivity);
    });

    alert(allActivities); // Alert box is empty
}

I need the array allActivities to be global so that I can access it outside of the .get function. So I need the last code example to work. In other words, the last code example needs to alert the content.

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
Einar
  • 1,001
  • 3
  • 11
  • 28
  • JavaScript is asynchronous language. the execution flow doesn't stop for ajax calls. In this case, `alert` get executed while ajax call waiting for the text file. – Venugopal Dec 23 '15 at 05:54
  • $.get is asynchronous, so your array has not yet been populated when you alert – Brian Driscoll Dec 23 '15 at 05:55
  • you are not messing anything. That is an asynchronous function and will fill up your variable. You just need to do all the other things after it filled up. Perhaps define a function and call it after you initialize that array. – Aᴍɪʀ Dec 23 '15 at 05:55
  • Ohh. So my global array is working? So if I trigger alert with button after page load it will work? – Einar Dec 23 '15 at 05:56
  • 1
    @Einar yes, it will. – Aᴍɪʀ Dec 23 '15 at 05:56
  • 3
    @Venugopal JavaScript is not inherently asynchronous. – Brian Driscoll Dec 23 '15 at 05:56
  • @BrianDriscoll, true, its made asynchronous via ajax, event handlers etc. thanks for pointing out – Venugopal Dec 23 '15 at 06:01
  • 1
    http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call and http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – epascarello Dec 23 '15 at 06:02

1 Answers1

1

Gathered from comments:

Since $.get is asynchronous the alert is called before my array is populated. The global array is working as expected. The alert needs to be called at a later point, for instance with a button click after page load.

I have tested it and it worked.

Einar
  • 1,001
  • 3
  • 11
  • 28