0

I am trying to dynamically create variables in javascript. In my PHP code I already dynamically create variables from SQL output which gives me $res1, $res2, etc. Now I want to use these in my javascript but of course I cannot hardcode it for I can never know how many of the $res variables the PHP will generate.
I have the feeling I am already fairly close though. I have the following:

var i=1;
while (i<=count) {
    var name = "<?php ${"res".$_GET['i']} ?>";
}
logos
  • 61
  • 1
  • 8
  • Try passing the variables back in an array, then do a foreach through them. – Kiee Aug 26 '14 at 06:35
  • Take a look at this question: http://stackoverflow.com/questions/12414408/how-to-store-a-string-in-a-javascript-variable-that-has-single-quotes-and-double/12414551#12414551. It may help you. – Luka Aug 26 '14 at 06:37
  • Thank you guys, your reactions helped me and i've got it working now by using an array and using json_encode to use the array in javascript.
    Sebcap26, it is indeed related to passing variables from php to javascript but as you probably see my problem is passing variables + combining javascript and php variables to create a javascript variable.
    – logos Aug 26 '14 at 07:02

2 Answers2

1

Put the PHP data in an array. Then you can convert the PHP array to a JS array with json_encode():

var res = <?php echo json_encode($res) ?>;
for (var i = 0; i < res.length; i++) {
    var name = res[i];
    // Do something with name
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

The php will be ran once after the server request, so $_GET[i] will only have one value for the entire loop. Which I'm presuming is not your desired effect.

Try handling the variables on the backend and pushing them all into a array then sending that to the browser.

for (var i = 0; i < data.length; i++) {
    var name = data[i];
}

where data is an array sent back from the server.

Kiee
  • 10,661
  • 8
  • 31
  • 56