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 h
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"]
You should try this instead:
var data = <?= $data ?>
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)
{
...
}
});
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
Be sure you're echo
ing 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.
Not sure if <? $data; ?>
is a typo or not but you should be using either <?=$data;?>
or <?php echo $data; ?>