Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using JSON in PHP, and now I need to access it from JavaScript. How do I pass a JSON object to JavaScript?

<?php
    $array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
    $json = json_encode($array);
>

where My.js has:

showAll(){
    alert("Show All Json Objects");
    // How do I get the JSON value here?
}

How can I do it?

share|improve this question
add comment (requires an account with 50 reputation)

3 Answers

up vote 5 down vote accepted

Assuming that you're using Ajax as your method to download the JSON, you would echo the result of the json_encode:

<?php
    $array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");

    echo json_encode($array);
?>

And then within your call back event, you'd eval the response:

var obj = eval('(' + req.ResponseText + ')');
for(var i in obj) {
    alert(i + ': ' + obj[i]);
}

Assuming that you have an XMLHttpRequest object with the name req.

share|improve this answer
add comment (requires an account with 50 reputation)

You could request the JSON data with AJAX or you could pass the data from PHP to JavaScript as a JavaScript variable:

$array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
$json = json_encode($array);

echo '<script type="text/javascript">';
echo 'var myJson = "' . $json . '";';
echo '</script>';

edit: you have to eval the json string, otherwise you will just have a string not a object...

Off course keeping in mind all the guidelines about mixing PHP/HTML/JavaScript...

share|improve this answer
I would submit a +1 for doing it via ajax instead, since you can then simply eval the returned json snippet and you don't have to worry about mixing php/javascript/html. – localshred Jan 20 '09 at 7:25
add comment (requires an account with 50 reputation)
<?php
$array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
$json = json_encode($array);
?>
<script type="text/javascript">
var myjson = <?php echo $json; ?>;
</script>
share|improve this answer
Actually this is the best answer of all, you can put JSON data directly in javascript like in answer, it's documented on official json page. Thanks. – s3m3n May 16 at 23:26
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.