json_encode() is corePHP function which is used to generate JSON which will be a simple value (i.e nethier an object nor an array). So, in this tutorial, we will see how to use json_encode() function to pass PHP array to Javascript.
PHP code:
<?php
$data = array(
array('name'=>'pankaj', 'email'=>'Pankaj@gmail.com'),
array('name'=>'Ayush', 'email'=>'Ayush@gmail.com')
);
?>
JavaScript Code:
<script>
getUserInfo(<?php echo json_encode($data); ?>)
function getUserInfo(userObj){
alert(JSON.stringify(userObj)); //convert object into string.
}
</script>
Code Explanation :-
In the above code, $data variable holds a multidimensional array which will pass to JavaScript with the help of json_decode().
<?php echo json_encode($data); ?>
Above line will convert $data array into simple values.
you can see the Javascript comment line, I have used one more function i.e JSON.stringify. JSON.stringify is Javascript function which is used to Convert JavaScript object into a string.
Output:
0 Comment(s)