Here is a JavaScript example on the client-side, making an AJAX request to fetch the PHP file from the previous example:
Use JSON.parse()
to transform the result into a JavaScript object.
const xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById(“demo”).innerHTML = myObj.name; } xmlhttp.open(“GET”, “demo_file.php”); xmlhttp.send(); |
When using the PHP function json_encode(), arrays in PHP are also converted into JSON.
<?php $myArr = array(“John”, “Mary”, “Peter”, “Sally”); $myJSON = json_encode($myArr); echo $myJSON; ?> |
Here is a JavaScript example on the client-side, making an AJAX request to retrieve the PHP file from the array example mentioned above.
Use JSON.parse() to convert the result into a JavaScript array.
var xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { const myObj = JSON.parse(this.responseText); document.getElementById(“demo”).innerHTML = myObj[2]; } xmlhttp.open(“GET”, “demo_file_array.php”, true); xmlhttp.send(); |