Dear All I am using Json in php, Now I need to access it from javascript, How to pass 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 to get the json value here

        }

Anyone help me how to do it?

share|improve this question

78% accept rate
feedback

3 Answers

up vote 3 down vote accepted

Assuming that your 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.

hth

Gavin

share|improve this answer
feedback

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
feedback
<?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
feedback

Your Answer

 
or
required, but never shown
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.