0

I have a file that I want to read into a variable in JS to use it later

var states;
$.get('states.json', function(data) {
        states=data;
        alert(data);
        alert(states);
    }, "text");

 alert(states);

In the above code, value of states is that of the file inside the function, but it is null outside.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
user2612159
  • 37
  • 1
  • 6
  • 3
    You need to understand how asynchronous calls work in javascript. – Matt R Mar 18 '14 at 17:20
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – T.J. Crowder Mar 18 '14 at 17:21

2 Answers2

3

That's because the alert at the end runs before the file is received. Ajax is asynchronous by default.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • OK so my code should wait till the file is completely fetched before proceeding further. `var states; $.get('states.json', function(data) { states=data; alert(data); alert(states); }, "text"); //alert(states); var Cstates = Ext.create('Ext.data.Store', { //combo box data fields: ['abbr', 'name'], data: states }); ` this is the code later in the file, can i hold it till the value is fetched into the variable?? – user2612159 Mar 18 '14 at 17:23
  • @user2612159: The point is to call whatever code you need to use the data with from within the callback, because that's when you know it's there and ready. You can't stop the execution and wait for it (or you could look at it that that's *how* you do that). – T.J. Crowder Mar 18 '14 at 17:25
0

There's an ultra helpful function I learned recently jQuery has with AJAX that might be of use to you.

var states;
$.get('states.json', function(data) {
    states=data;
    alert(data);
    alert(states);
}, "text").done(function(result) {console.log(result);};

That should print out the states. Check out the API for AJAX here: https://api.jquery.com/jQuery.ajax/

floatingeye
  • 113
  • 8