Jenski
Jenski

Reputation: 1468

Returning an array from a PHP function to jQuery

I have a PHP function that returns an array. What is the best way to "receive" this using jQuery?

Upvotes: 2

Views: 1477

Answers (4)

David Barnes
David Barnes

Reputation: 2148

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) . ';'
?>

Upvotes: 3

keithjgrant
keithjgrant

Reputation: 12739

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.

Upvotes: 2

Wookai
Wookai

Reputation: 21723

Encode it in JSON using json_encode(), print it to the page and then call this page using jQuery (with $.get() for example).

Upvotes: 1

jkndrkn
jkndrkn

Reputation: 4062

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.

Upvotes: 10

Related Questions