Reputation: 480
code:
<?php
mysql_connect("localhost", "bikemap", "pedalhard") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$data = mysql_query("SELECT * FROM gpsdata");
$aData = array();
while($row = mysql_fetch_assoc($data))
$aData[$row['idgpsdata']] = array($row);
$json = json_encode($aData);
?>
var json = "<?php echo $json; ?>";
document.write(json.length);
alert('half done');
for(var x=0; x < json.length; x++) {
document.write("<li>"+ x + " " + json[x]+ "</li>");
}
Output of the code:
20
0 <
1 ?
2 p
3 h
4 p
5
6 e
7 c
8 h
9 o
10
11 $
12 j
13 s
14 o
15 n
16 ;
17
18 ?
19 >
if you take out the line numbers is: "<?php echo $json; ?>"
Looks suspiciously like a line where I'm trying to transfer the php variable $json to javascript variable json.
I've tried every type of bracketry and quote to get this to work. Anyone see any mistakes or have any suggestions?
Upvotes: 0
Views: 1879
Reputation: 172
Try
var json = {<?php echo $json; ?>};
or maybe
var json = eval("{<?php echo $json; ?>}");
Be sure your code is interpreted as php by the server. The file extension '.js' is usually not configured in this way.
If you want to embed your php file as a js, you'd better to rename it as .php and add the required header like that :
<?php
header("Content-type","text/javascript");
?>
var json = {<?php echo $json; ?>};
Upvotes: 1
Reputation: 2623
You could do it other way, that is, put your javascript inside php:
echo "<script>
var json = $json;
document.write(json.length);
alert('half done');
for(var x=0; x < json.length; x++) {
document.write(\"<li>\"+ x + \" \" + json[x]+ \"</li>\");
}
</script>";
Upvotes: 0
Reputation: 27486
You could try:-
var json = <? echo $json ?>;
You cannot execute php code inside the Javascript. Instead you must get php to write the relevent javascript code;
Upvotes: 0