I have a PHP function that returns an array. What is the best way to "receive" this using jQuery?
+10
A:
Use json_encode() to turn your PHP array into a native JavaScript array, then use jQuery $.post, $.get, or $.ajax methods to fetch this value from your PHP script. I generally use $.post unless I need the special features that $.ajax provides.
jkndrkn
2009-11-24 16:15:10
+1
A:
Encode it in JSON using json_encode(), print it to the page and then call this page using jQuery (with $.get() for example).
Wookai
2009-11-24 16:15:17
+2
A:
I echo what jkndrkn and Wookai said, but I would add that if you're not using ajax, you can still use json_encode() to insert the array directly into your javascript/jquery code.
keithjgrant
2009-11-24 16:19:20
+2
A:
I use smarty, and this is how I do it:
<?php
$smarty = new Smarty;
$array = array('foo' => 'bar', 'bar' => 'foo');
$smarty->assign('array', $array);
$smarty->display('template.htm');
?>
template.htm:
<html>
<head>
<script type="text/javascript">
var array = {$array|@json_encode};
</script>
</head>
<body>
</body>
</html>
If you don't use smarty you can do something like this:
<?php
$array = array('foo' => 'bar', 'bar' => 'foo');
echo 'var array = ' . json_encode($array) . ';'
?>
David Barnes
2009-11-25 04:39:44
Yes this is a smarty app im building... that is such a tidy way! Thanks for sharing!
Jenski
2009-11-25 09:19:42