Assign javascript vars using php and foreach...possible?
Posted: Sat Jan 20, 2007 11:15 pm
I have a database full of all kinds of goods that I need to print out in a javascript tree structure. I know javascript could access the database and assign the vars to js, but I'm already calling it using php for something else, so I want to kill 2 cats with one shovel.
So I want to call my database with php and write the values to an array. Then I want to loop through the array in php and write all variables to javascript variables. I could then use the variables later in the <script> section.
Here's an (incorrect) example of what I think should work. Use it as a jumping off point if you like...
Is this possible? I can't get it to actually write the variables to javascript. I've messed with alterations of the above code, as my attempts usually result in fatal errors. Story of my life...
So I want to call my database with php and write the values to an array. Then I want to loop through the array in php and write all variables to javascript variables. I could then use the variables later in the <script> section.
Here's an (incorrect) example of what I think should work. Use it as a jumping off point if you like...
Code: Select all
<?php
//----assume I already pulled all the array values out and stored them in array called $theArray
$i=1;
foreach($theArray as $value){
echo '<script> var theVar'.$i.' = "'.= $fred2 .'"; </script>';
$i++;
}
//----now test that at least the first js var was written...
?>
<script>
document.write(theVar1)
</script>