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?
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 edited Apr 19, 2013 at 1:48 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jan 20, 2009 at 7:05 venkatachalamvenkatachalam 102k31 gold badges74 silver badges77 bronze badges3 Answers
Reset to default 6Assuming 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
.
<?php
$array = array("a"=>"Caucho", "b"=>"Resin", "c"=>"Quercus");
$json = json_encode($array);
?>
<script type="text/javascript">
var myjson = <?php echo $json; ?>;
</script>
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...