user2612159
user2612159

Reputation: 37

Read a text file to a variable in JavaScript

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.

Upvotes: 0

Views: 156

Answers (2)

floatingeye
floatingeye

Reputation: 113

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/

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074276

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

Upvotes: 3

Related Questions