I am trying to test the following code for inserting the value from PHP code to my javascript variable x
tested the PHP code, and it’s giving the correct output but the alert box in the javascript shows this –
date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000″; $query = mysql_query($myquery); if ( ! $myquery ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } //echo json_encode($data); echo ”; mysql_close($server); ?>
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Testing </title> <script type="text/javascript" src="jquery-1.9.1.min.js"></script> </head> <body> <?php $username='user'; $password='pass'; $host='xx.xx.xx.xx'; $database='abc'; $server = mysql_connect($host, $username, $password); $connection = mysql_select_db($database, $server); $myquery = 'select code a,sum(fee) b from xyz where date > date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000'; $query = mysql_query($myquery); if ( ! $myquery ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } //echo json_encode($data); echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">'; mysql_close($server); ?> <script type="text/javascript"> function test(){ var x = document.getElementById("myPhpValue").value; alert(x); } test(); </script> </body> </html>
Advertisement
Answer
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
Then:
var x = document.getElementById("myPhpValue").value;
you need to insert id="myPhpValue"
, because you used the "getElementById";