The PHP File
PHP has some built-in functions to handle JSON.
Objects in PHP can be converted into JSON by using the PHP function json_encode():
Step 1:
Create index.html file and create below html code in it.
<h2 id="demo1"></h2>
Step 2:
Create php file to access json data.
PHP Array
Arrays in PHP will also be converted into JSON when using the PHP function json_encode():
demo_json.php<?php $myArr = array("John", "Mary", "Peter", "Sally"); $myJSON = json_encode($myArr); echo $myJSON; ?>
The Client JavaScript
Here is a JavaScript on the client, using an AJAX call to request the PHP file from the array example above:Use JSON.parse() to convert the result into a JavaScript array:
<script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo1").innerHTML = myObj[2]; } }; xmlhttp.open("GET", "demo_json.php", true); xmlhttp.send(); </script>
Complete Code For Getting JSON Array 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> <br> <br> <div class="text-center"> <h1 id="color" style="color: tomato">How To Get JSON Data From PHP File Using JavaScript</h1> </div> <br> <br> <br> <div class="well"> <h2 id="demo1"></h2> </div> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo1").innerHTML = myObj[2]; } }; xmlhttp.open("GET", "demo_json.php", true); xmlhttp.send(); </script> </div> </body> </html>