0

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?

5
  • Right click -> view source... What you see is not valid javascript. Commented Apr 15, 2014 at 21:55
  • How is it now working? What is the error? What is actually happening? Commented Apr 15, 2014 at 21:55
  • if i try to call the function it says the function does not exist, but if i comment out the first line of the function it works fine Commented Apr 15, 2014 at 21:56
  • where exactly do you attempt to call it? Commented Apr 15, 2014 at 22:05
  • Is it possible you cannot use this function on local files for security reasons? Perhaps your host doesn't allow it. Or you use Windows? I think there is a documented bug on Windows related to this function, but I'm not sure it's relevant to your case. Commented Apr 15, 2014 at 22:05

2 Answers 2

1
<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.

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

6 Comments

i still get "test is not defined" when i attempt to call the function
In this case, your json file must be wrongly formatted. Have you viewed the source?
in php i'm using file_put_contents('vars.txt', json_encode($varsphp)); to write json data to the file
my file itself looks like this [null,"offline.png","offline.png","offline.png","offline.png","offline.png","offline.png","Group A","Group B","Group C","Group D","Group E","Group F","","","","","","","0","0","0","0","0","0"]
The file looks ok, but what is actually rendered into the page? You really need to view source.
|
0

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

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

1 Comment

still saying function is not defined when i use this, if i comment it out the function works fine

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.