PHP Dynamic JSON Data File with Ajax Processing

Published :
Author :
Adam Khoury
Learn to make a PHP script impersonate a JSON data file so that you can generate dynamic JSON data files from server side MySQL database information. Or use it to dynamically fetch and render static .json files on the server. my_json_list.php <?php header("Content-Type: application/json"); $jsonData = file_get_contents("mylist.json"); echo $jsonData; ?> JSON_tutorial_3.html <!DOCTYPE html> <html> <head> <script> function ajax_get_json(){ var results = document.getElementById("results"); var hr = new XMLHttpRequest(); hr.open("GET", "my_json_list.php", true); hr.setRequestHeader("Content-type", "application/json"); hr.onreadystatechange = function() { if(hr.readyState == 4 && hr.status == 200) { var data = JSON.parse(hr.responseText); results.innerHTML = ""; for(var obj in data){ results.innerHTML += data[obj].user+" is "+data[obj].age+" and lives in "+data[obj].country+"<hr />"; } } } hr.send(null); results.innerHTML = "requesting..."; } </script> </head> <body> <div id="results"></div> <script>ajax_get_json();</script> </body> </html>