Access a PHP array from JavaScript

bigbksmedspro

New Member
I have the following code where I declare a PHP array variable and inside a function, I put some data into the array. I also display buttons mapped to each index of the array that will show the data in the PHP array for that index number.When testing on a browser, I don't get the right answer. I checked the page source, it had code like \[code\]data_array = ["<?php echo implode ('',Array); ?>"];\[/code\] instead of the text from the Array.What am I doing wrong and what should I do to get the correct output? (BTW, I tried to execute the same without declaring the function and it seemed to work, but I need a function for my work and can't take that approach).\[code\]<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"<html lang="en"> <head> <title>Example</title> <?php $giant_says = array(); function display() { global $giant_says; $giant_says[] = "<a href='http://www.google.com'>Google</a>"; $giant_says[] = "Yahoo!"; $giant_says[] = "Bing"; echo "<div id='content'>"; echo $giant_says[0]; echo "</div><br><br>"; $i = 0; while($i < count($giant_says)) { echo "<input type='button' value='".$i."' onClick=\"addtext(".$i.");return false;\""; $i += 1; } } ?> <script type="text/javascript"> function addtext(index) { giantSays = ["<?php echo implode ('","', $giant_says); ?>"]; document.getElementById('content').innerHTML = giantSays[index]; } </script> </head> <body> <?php display(); ?> </body></html>\[/code\]
 
Back
Top