user1547167
user1547167

Reputation: 27

pull JSON data from a text file and put it in an array in javascript

i have a text file named "vars.txt" that holds an array. How can i pull that information and put it in a javascript array? right now i have

<script type="text/javascript">
function test() {
  var testvar = <?php file_get_contents('vars.txt') ?>;
  alert ("success");
  alert (testvar);
};
</script>

and that is not working. is there a better way to pull this data into an array?

Upvotes: 0

Views: 113

Answers (2)

user2699477
user2699477

Reputation:

Use json_decode() to decode the JSON data from vars.txt:

var testvar = <?php echo json_decode(file_get_contents('vars.txt')) ?>;

Upvotes: 0

Drahcir
Drahcir

Reputation: 11972

<script type="text/javascript">
function test() {
  var testvar = <?php echo file_get_contents('vars.txt') ?>;
  alert ("success");
  alert (testvar);
};
</script>

You forgot to echo the data, without this nothing will be rendered into the javascript function.

To debug situations like this, just view the source of the rendered webpage, and see what's actually printed.

Upvotes: 1

Related Questions