The Client JavaScript
Step 1:
Create index.html and implement code in it.
<h2 id="demo1"></h2>
Step 2:
Implement java script to access data from php file
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("demo1").innerHTML = myObj.name; } }; xmlhttp.open("GET", "demo_json.php", true); xmlhttp.send();
Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above
Step 4:
Create Demo_json.php file to access json data
<?php $myObj->name = "shiva"; $myObj->age = 30; $myObj->city = "New York"; $myJSON = json_encode($myObj); echo $myJSON; ?>
Complete Code For Getting JSON data from PHP File Using JavaScript
<!DOCTYPE html> <html> <head> <title>How To Get JSON data from PHP File Using JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">How To Get JSON data from PHP File Using JavaScript</h1> </div> <br> <div class="well"> <h2 id="demo1"></h2> </div> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("demo1").innerHTML = myObj.name; } }; xmlhttp.open("GET", "demo_json.php", true); xmlhttp.send(); </script> </div> </body> </html>