Sir
Sir

Reputation: 8277

PHP arrays into javascript arrays

I am a bit confused here on how I implement an array into JS from PHP....

I'm doing this for testing - eventually I'll use long polling or websockets if they get highly supported but this is what I have:

$get = mysql_query("SELECT x,y,sid FROM player_town WHERE uid='1'") or die(mysql_error());
$row = mysql_fetch_assoc($get);
$data = json_encode($row);

Further down the script I then put in the head:

<script>var data = Array(<? $data; ?>)</script>
<script type="text/javascript" src="js.js"></script>

But in js.js it says undefined but $data is set. This is the error:

x is not defined

In js.js I did alert(data[x]); and I get undefined.

My json_encode looks like this:

{"x":"283","y":"99","sid":"1"}

Any ideas?

Upvotes: 0

Views: 177

Answers (6)

DvideBy0
DvideBy0

Reputation: 688

I agree with the answer in your comments. I would make an AJAX call to yourFile.php and then send back your JSON encoded response. so here would be my psuedo code.

1. Make AJAX request

$.ajax({
    url: "yourFile.php",
    dataType: 'json',
    success: function(data)
    {
         console.log(data);
    }
});

2. Make sure that your PHP file also returns header for JSON

header('Content-type: application/json');

2. Return {"x":"283","y":"99","sid":"1"} as data on your ajax request


3. call the values by using data.x or data.y or data.sid

Upvotes: 1

Andreas Wong
Andreas Wong

Reputation: 60594

Not sure why you need to wrap the json string in an Array, you could just do

var data = <?php echo $data; ?>;

--

To get the value of data in your js, you can either do data.x or data["x"]

Upvotes: 4

Kurt
Kurt

Reputation: 7212

You can use AJAX (much easier). Make your PHP script echo $data, and then using jQuery ajax request the data in your HTML file as JSON. For example:

$.ajax({
    url: script_url,
    dataType: 'json',
    success: function(json)
    {
         ...
    }
});

Upvotes: 1

Ryan Kempt
Ryan Kempt

Reputation: 4209

Not sure if <? $data; ?> is a typo or not but you should be using either <?=$data;?> or <?php echo $data; ?>

Upvotes: 1

seeming.amusing
seeming.amusing

Reputation: 1179

You should try this instead:

var data = <?= $data ?>

Upvotes: 1

rjz
rjz

Reputation: 16510

Be sure you're echoing the PHP data into the <script> tags

<script>var data = Array(<?php echo $data; ?>)</script>

As an aside, it's a good idea to avoid using short tags (<? and ?>) in a production setting--many servers have them disabled by default, and it's a really annoying way to have your code break.

Upvotes: 1

Related Questions