2

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

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Yes this is a smarty app im building... that is such a tidy way! Thanks for sharing!
I really like this idea, too bad I get the "Uncaught SyntaxError: Unexpected identifier" error :/
2

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.