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); ?>
JavaScript
x
42
42
1
<html>
2
<head>
3
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
4
<title>Testing </title>
5
6
7
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
8
</head>
9
<body>
10
<?php
11
$username='user';
12
$password='pass';
13
$host='xx.xx.xx.xx';
14
$database='abc';
15
$server = mysql_connect($host, $username, $password);
16
$connection = mysql_select_db($database, $server);
17
$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';
18
$query = mysql_query($myquery);
19
if ( ! $myquery ) {
20
echo mysql_error();
21
die;
22
}
23
$data = array();
24
for ($x = 0; $x < mysql_num_rows($query); $x++) {
25
$data[] = mysql_fetch_assoc($query);
26
}
27
//echo json_encode($data);
28
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
29
30
mysql_close($server);
31
?>
32
33
<script type="text/javascript">
34
function test(){
35
var x = document.getElementById("myPhpValue").value;
36
alert(x);
37
}
38
test();
39
40
</script>
41
</body>
42
</html>
Advertisement
Answer
JavaScript
1
2
1
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
2
Then:
JavaScript
1
2
1
var x = document.getElementById("myPhpValue").value;
2
you need to insert id="myPhpValue"
, because you used the "getElementById";