0

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?

10
  • 1
    Are you sure that the PHP code is being executed? That is, are you requesting the page from a web server with PHP enabled or are you just opening the page from the file system in the browser? Commented Nov 16, 2011 at 4:41
  • @VincentRamdhanie I am running the code from a site hosted with PHP enabled. Commented Nov 16, 2011 at 4:43
  • @LorenZimmer, why don't you "view source" on the output of your script and show us that. Commented Nov 16, 2011 at 4:44
  • stackoverflow.com/questions/168214/… Commented Nov 16, 2011 at 4:44
  • @Brad this kind of development is new to me where would I "view source" from? Commented Nov 16, 2011 at 4:51

3 Answers 3

1

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; ?>};
Sign up to request clarification or add additional context in comments.

1 Comment

I needed just the php file to pass the variables
0

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;

Comments

0

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>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.