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.

2

2 Answers 2

3

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

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

2 Comments

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: 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).
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/

Comments

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.