Learn How To Display JSON Data In PHP With Easy Method

admin_img Posted By Bajarangi soft , Posted On 24-09-2020

Display JSON data in a PHP

json_with_php

JSON with PHP

  • JSON stands for the JavaScript Object Notation.
  • JSON used to exchanging and storing the data from the web-server.
  • PHP has some built-in functions to handle JSON.
  • Objects in PHP can be converted into JSON by using the PHP function
json_encode()
 

Let's learn


1.PHP Files with client JavaScript: 

  • Create array.php file

  • The data form the object of the php are to be encoded into JSON format.

array.php

<?php
$myObj = new stdClass();
$myObj->name = "student_1";
$myObj->school="CBHS school";
$myObj->age = 10;
$myObj->class = 5;

$myJSON = json_encode($myObj);

echo $myJSON;
?>
 
  • From the array.php  file the data is being sent to the JSON through the “echo” and the data will be responded in the JavaScript of the client.

  • Execute below code.
     

<!DOCTYPE html>
<html lang="en">
<head>
        <title>JSON with PHP</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">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
        <div class="text-center">
                <h1>JSON with PHP</h1>
            </div>
        <br>
        <h2>Get data as JSON from a PHP file on the server.</h2>
        <div class="well">
                <h5>Student Name:</h5>
                <p id="demo"></p>
                <script>
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    myObj = JSON.parse(this.responseText);
                    document.getElementById("demo").innerHTML = myObj.name;
                }
            };
            xmlhttp.open("GET", "array.php", true);
            xmlhttp.send();
        </script>
            </div>
        <br>
</div>
</body>
</html>

 
 

 

2.PHP Array with client JavaScript: 

  • Create array_1.php file

  • Create array in it . 

array_1.php

<?php
$array = array(
        "student_1",
    "student_2",
    "student_3",
    "student_4",
    "student_5",
    "student_6",
    "student_8"
);

$arrJSON = json_encode($array);

echo $arrJSON;
?>
 
  • From the array_1.php  file the data is being sent to the JSON through the “echo” and the data will be responded in the JavaScript of the client.

  • Execute below code.
     

<!DOCTYPE html>
<html lang="en">
<head>
        <title>JSON with PHP</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">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
        <div class="text-center">
                <h1>JSON with PHP</h1>
            </div>
        <br>
        <h2>Get data as JSON from a PHP file, and convert it into a JavaScript array.</h2>
        <div class="well">
                <p id="demos"></p>
                <script>
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var myObj = JSON.parse(this.responseText);
                    document.getElementById("demos").innerHTML = myObj[2];
                }
            };
            xmlhttp.open("GET", "array_1.php", true);
            xmlhttp.send();
        </script>
            </div>
        <br>
</div>
</body>
</html>




3.PHP DATABASE with client JavaScript: 

  • Retrieve the data from the database so for that create database.php file to connect database .

database.php

<?php
$host         = "localhost";
$username     = "root";
$password     = "";
$dbname       = "school";
$result_array = array();
/* Create connection */
$conn = new mysqli($host, $username, $password, $dbname);
/* Check connection  */
if ($conn->connect_error) {
        die("Connection to database failed: " . $conn->connect_error);
}
/* SQL query to get results from database */
$sql = "SELECT name FROM class ";
$result = $conn->query($sql);
/* If there are results from database push to result array */
if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
                array_push($result_array, $row);
    }
}
/* send a JSON encded array to client */
echo json_encode($result_array);
$conn->close();
?>
 
  • From the database.php  file the data is being sent to the JSON through the “echo” and the data will be responded in the JavaScript of the client.

  • Execute below code.
     

<!DOCTYPE html>
<html lang="en">
<head>
        <title>JSON with PHP</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">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
        <div class="text-center">
                <h1>JSON with PHP</h1>
            </div>
        <br>
        <h2>Get data from database as JSON from a PHP file on the server.</h2>
        <div class="well">
                <p id="arrayContent"></p>
                <script>
            var obj, xmlhttp;
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("arrayContent").innerHTML =
                        this.responseText;
                }
            };
            xmlhttp.open("GET", "database.php", true);
            xmlhttp.send();
        </script>
            </div>
        <br>
</div>
</body>
</html>




3.PHP Loop with client JavaScript: 

  • Retrieve the data from the database so for that create database_2.php file to connect database(as previous).

  • From the database_2.php file the data is being sent to the JSON through the “echo” and the data will be responded in the JavaScript of the client.

  • Execute below code.

database_2.php

<!DOCTYPE html>
<html lang="en">
<head>
        <title>JSON with PHP</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">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
        <div class="text-center">
                <h1>JSON with PHP</h1>
            </div>
        <br>
        <h2>Get data from database as JSON from a PHP file on the server using for loop.</h2>
        <div class="well">
                <p id="dem"></p>
                <script>
            var obj, dbParam, xmlhttp, myObj, x, txt = "";
            obj = { "limit":10 };
            dbParam = JSON.stringify(obj);
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    myObj = JSON.parse(this.responseText);
                    for (x in myObj) {
                        txt += myObj[x].name + "<br>";
                    }
                    document.getElementById("dem").innerHTML = txt;
                }
            };
            xmlhttp.open("GET", "database.php", true);
            xmlhttp.send();
        </script>
            </div>

        <br>
</div>
</body>
</html>




3.PHP Method = POST  

  • When sending data to the server, it is often best to use the HTTP POST method.

  • POST method the arguments have to be passed.

  • GET method the arguments can passed when the request of the php file sent.

  • Retrieve the data from the database so for that create post.php file to connect database..

post.php

 

<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_POST["x"], false);
$conn = new mysqli("localhost", "root", "", "school");
$stmt = $conn->prepare("SELECT name FROM class LIMIT ?");
$stmt->bind_param("s", $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
​​
  • From the post.php file the data is being sent to the JSON through the “echo” and the data will be responded in the JavaScript of the client.
  • The only difference in the PHP file is the method for getting the transferred data.

  • Execute below code
     

<!DOCTYPE html>
<html lang="en">
<head>
        <title>JSON with PHP</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">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
        <div class="text-center">
                <h1>JSON with PHP</h1>
            </div>
        <h2>Get data from database as JSON from a PHP file on the server using PHP method loop.</h2>
        <div class="well">
                <p id="data_fetch_php_method"></p>
                <script>
            var obj, dbParam, xmlhttp, myObj, x, txt = "";
            obj = { "limit":10 };
            dbParam = JSON.stringify(obj);
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    dataobj = JSON.parse(this.responseText);
                    for (x in dataobj) {
                        txt += dataobj[x].name + "<br>";
                    }
                    document.getElementById("data_fetch_php_method").innerHTML = txt;
                }
            };
            xmlhttp.open("POST", "post.php", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send("x=" + dbParam);
        </script>
            </div>
        <br>
</div>
</body>
</html>



Complete Code of JSON with PHP Function:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSON with PHP</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">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>JSON with PHP</h1>
    </div>
    <h2>Get data as JSON from a PHP file on the server.</h2>
    <div class="well">
        <h5  id="demo"></h5>
        <script>
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    myObj = JSON.parse(this.responseText);
                    document.getElementById("demo").innerHTML = myObj.name;
                }
            };
            xmlhttp.open("GET", "array.php", true);
            xmlhttp.send();
        </script>
    </div>

    <h2>Get data as JSON from a PHP file, and convert it into a JavaScript array.</h2>
    <div class="well">
        <p id="demos"></p>
        <script>
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    var myObj = JSON.parse(this.responseText);
                    document.getElementById("demos").innerHTML = myObj[2];
                }
            };
            xmlhttp.open("GET", "array_1.php", true);
            xmlhttp.send();
        </script>
    </div>
    <h2>Get data from database as JSON from a PHP file on the server.</h2>
    <div class="well">
        <p id="arrayContent"></p>
        <script>
            var obj, xmlhttp;
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("arrayContent").innerHTML =
                        this.responseText;
                }
            };
            xmlhttp.open("GET", "database.php", true);
            xmlhttp.send();
        </script>
    </div>
    <h2>Get data from database as JSON from a PHP file on the server using for loop.</h2>
    <div class="well">
        <p id="data_fetch"></p>
        <script>
            var obj, dbParam, xmlhttp, myObj, x, txt = "";
            obj = { "limit":10 };
            dbParam = JSON.stringify(obj);
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    myObj = JSON.parse(this.responseText);
                    for (i in myObj) {
                        txt += myObj[i].name + "<br>";
                    }
                    document.getElementById("data_fetch").innerHTML = txt;
                }
            };
            xmlhttp.open("GET", "database.php", true);
            xmlhttp.send();
        </script>

    </div>
    <h2>Get data from database as JSON from a PHP file on the server using PHP method loop.</h2>
    <div class="well">
        <p id="data_fetch_php_method"></p>
        <script>
            var obj, dbParam, xmlhttp, myObj, x, text = "";
            obj = { "limit":10 };
            dbParam = JSON.stringify(obj);
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    dataobj = JSON.parse(this.responseText);
                    for (x in dataobj) {
                        text += dataobj[x].name + "<br>";
                    }
                    document.getElementById("data_fetch_php_method").innerHTML = text;
                }
            };
            xmlhttp.open("POST", "post.php", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send("x=" + dbParam);
        </script>
    </div>
    <br>
</div>
</body>
</html>


 

Related Post