I saw many examples related but I'm still confused. I'm using ajax (which I don't know much about) to get the results of a file updated every xxx seconds. It's working perfectly if I pass just one variable, but what is the best way if I need to pass an array from php through it?
Structure is simples:
show_results.php
<?php
include_once('modWhosonlineCustom.inc.php');
$document->addScript("http://code.jquery.com/jquery-latest.js");
$document->addScript("ajax.js");
$array_name = modWhosonlineCustom::getOnlineUserNames();//the array I need to pass to javascript variable
?>
<script>
var whosonline = '<?php echo "$array_name"; ?>';
</script>
<div id="results"></div>
Ajax code than would have more than one param to build in the url load:
ajax.js
$(document).ready(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]");
var refreshId = setInterval(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
And back to PHP response page, how could I use again the array params passed through url?
response.php
<?php
$names = $_GET['array_name'];
foreach ($names as $name) {
//do something
Any suggestions is really appreciated, thanks!
EDIT
Thanks guys, I think I'm the right way now, but ramains the problem to pass this array through a url in the javascript. Or maybe I'm not getting it in the right way in the php end callback file. I'll show you what a modifyed:
show_results.php
...
<?php
$names = modWhosonlineCustom::getOnlineUserNames();
?>
<script>
var whosonline = '<?php echo "json_encode($names)"; ?>';
</script>
ajax.js
$(document).ready(function() {
$("#atendentes").load("response.php?names=" + whosonline);
var refreshId = setInterval(function() {
$("#atendentes").load("response.php?names=" + whosonline + "&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
response.php
$users = $_GET['names'];
$users = json_decode($users);
echo "user: $users";
$names = $users;
foreach ($names as $name) {
...
Here in the other side I'm getting: Warning: Invalid argument supplied for foreach() in response.php on line 33, and the echo is empty
What is missing?
Your code wouldn't work. If you have
you actually get
as the output. Not the contents of the array. To "output" an array from PHP to JS, you have to convert it to native Javascript, which is where json_encode comes in:
which will produce
As a general rule, anytime you are using PHP to generate javascript code and are filling in Javascript variables with PHP values, you should use json_encode to ensure that you're generating valid Javascript. Any syntax errors and the whole Javascript code block is dead in the water once the client starts trying to execute it.
To pass arrays/objects from PHP to JavaScript you may use the
json_encode()
/json_decode()
functions.