Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavascript | JSON PHP

Javascript | JSON PHP

JSON stands for the JavaScript Object Notation. It is used to exchanging and storing the data from the web-server. JSON uses the object notation of JavaScript. JavaScript objects can be converted into the JSON and receive JSON format text into the JavaScript objects. Converting the JavaScript object into the JSON format is done by the given function: 
 

JSON.stringify(object)

Converting the JSON format into the JavaScript object is done by the given function: 
 

JSON.parse(string_format)

Exchanging the data from server, PHP as server language used. The JSON.parse() function is used to get the data from php or from the any other server. For the receiving the data from the server few AJAX statements to check whether the server is ready to respond the data from the server or not. If those conditions are fulfilled then the data from the php file can be received. The protocols used to sending and receiving the data from server is given by: 
 

XMLHttpRequest()

PHP Files and its client JavaScript: Consider a php file in which the object of the person are given with his personal data like name, gender, age are given into it. The data form the object of the php are to be encoded into JSON format. The given file is saved by neveropen.php
 

php




<?php
$myObj = new stdClass();
$myObj->name = "Geeks";
$myObj->college="NIT";
$myObj->gender = "Male";
$myObj->age = 30;
  
$myJSON = json_encode($myObj);
  
echo $myJSON;
?>


From the php file the data is being sent to the JSON via the “echo” and the data will be responded in the JavaScript of the client. In the php file json_encode() is used to convert the objects in the php file to json format. Accessing the data from php file via client JavaScript use the following script:
 

html




<!DOCTYPE html>
<html>
<body>
<h1 style = "color:#090; text-align:center;">neveropen</h1>
<p style="font-size:25px">
JSON get data from a PHP file on the server.
</p>
 
 
  
<h4>Author Name:</h4>
<p id="name"></p>
 
 
 
<h4>College:</h4>
<p id="college"></p>
 
 
  
<h4>Gender:</h4>
<p id="gender"></p>
 
 
  
<h4>Age:</h4>
<p id="age"></p>
 
 
  
<script>
  
var xmlhttp = new XMLHttpRequest();
  
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        document.getElementById("name").innerHTML = myObj.name;
        document.getElementById("college").innerHTML = myObj.college;
        document.getElementById("gender").innerHTML = myObj.gender;
        document.getElementById("age").innerHTML = myObj.age;
    }
};
xmlhttp.open("GET", "neveropen.php", true);
xmlhttp.send();
  
</script>
  
</body>
</html>


Output: 
 

json

In the Script JSON.parse(this.responseText) function is used to parse the data into variable so that it can call the values from that object. The this.response is used to take the data from the php that is being print as a string. In the given code the php object data is being taken extracted by script of the JSON. By the AJAX function in the script are checking the data whether it is responding are not when the it has responded the data will be sent and print in the web page. The xmlhttp.open(“GET”, “neveropen.php”, true) function is used to get the value from the php file neveropen.php. The xmlhttp.send() function is used to send the values in to the XMLHttpRequest().
PHP Array and its client JavaScript: Consider a php file which consists an array of the name. The data is encoded into the JSON and will be printed using the “echo”.
 

php




<?php
$arrDay = array(
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"
);
 
$arrJSON = json_encode($arrDay);
 
echo $arrJSON;
?>


Lets access the data from php file’s array using client JavaScript. To do so let us consider the following HTML file.
 

html




<!DOCTYPE html>
<html>
<body>
<h1 style = "color:#090; text-align:center;">neveropen</h1>
<p style="font-size:25px">JSON get data from PHP file,
                   and converting into JavaScript array.</p>
 
 
 
<p style = "font-size:25px;">Second Date of week: </p>
 
 
<p id="day"></p>
 
 
 
<script>
var xmlhttp = new XMLHttpRequest();
 
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("day").innerHTML = myObj[2];
    }
};
xmlhttp.open("GET", "daylist.php", true);
xmlhttp.send();
 
</script>
 
</body>
</html


Output: 
 

json

In the array is parsed to the variable in the JavaScript that value is being called by the array of js that is been initialised on the above line.
PHP Database: Retrieving the data from the database is just similar to getting the data from the normal php file. But the few additional queries to be added. In this process first data from the database has to be extracted to the php file and then that data has to be taken by the JavaScript to project it into client server. First create the MySQL database using the php. The following program is used to create a table and inserted few data into it. 
 

php




<?php
    $conn = new mysqli("localhost", "root", "", "neveropen");
     
    $createTable = "create table neveropen(names varchar(255))";
    $tableadd = $conn->query($createTable);
     
    $conn->query("insert into neveropen values('Geeks')");
    $conn->query("insert into neveropen values('gfg')");
    $conn->query("insert into neveropen values('g4g')");
     
    $conn->close();
?>


Now, extracting the data from other php script. 
 

php




<?php
    $conn = new mysqli("localhost", "root", "", "neveropen");
    $result = $conn->query("select names from neveropen");
 
    $output = array();
     
    $output = $result->fetch_all(MYSQLI_ASSOC);
    $sresult = json_encode($output);
     
    echo $sresult;
        $conn->close();   
?>


Now let us gather data in the client JavaScript and print the result. 
 

html




<!DOCTYPE html>
<html>
    <body>
        <h1 style = "color:#090; text-align:center;">neveropen</h1>
        <p style="font-size:25px">
         JSON received the data from the PHP file
        </p>
 
 
         
        <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", "data.php", true);
        xmlhttp.send();
        </script>
    </body>
</html>                   


In the following that is sent to client and printed the result in JSON structure since it is not filtered values into each different values. 
output: 
 

json get data

PHP Loop: This is the combination of the array and the above two topics (PHP Array and Its client JavaScript & PHP Database) with the integrating them with the loops in it. In this JavaScript parses the values into a variable those values are called by arrays and after printing the each myObj it’s values will be incremented to the next value. 
 

html




<!DOCTYPE html>
<html>
    <body>
        <h1 style = "color:#090; text-align:center;">neveropen</h1>
        <p style="font-size:25px">
         JSON received the data from the PHP file
        </p>
 
 
         
        <p id="arrayContent"></p>
 
 
         
        <script>
        var obj, xmlhttp, myObj, x, txt = "";
        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].names + "<br>";
                }
                document.getElementById("arrayContent").innerHTML = txt;
            }
        };
        xmlhttp.open("GET", "data.php", true);
        xmlhttp.send();
        </script>
    </body>
</html>       


Output: 
 

json get data

PHP Method = POST: It quiet simple if above topics had understood completely. In the following syntax changes will occur. In the POST method the arguments have to be passed via send method but in the GET method the arguments can passed when the request of the php file sent.
GET method: 
 

open("GET", file_name?x=argument, asyn, username, password)

POST method: 
 

open("POST", file_name, asyn, username, password)

The arguments are passed by the send(argument) method and send a request from the php to access data from server. So use function to get request are given below: 
 

setRequestHeader("Content-type", "application/x-www-form-urlencoded")

In the php file a header has to be added: 
 

header("Content-Type: application/json; charset=UTF-8")


The php file given below can be saved using post.php 
 

php




<?php
    header("Content-Type: application/json; charset=UTF-8");
    $obj = json_decode($_POST["x"], false);
    $conn = new mysqli("localhost", "root", "", "neveropen");
    $result = $conn->query("select names from ".$obj->table);
 
    $output = array();
     
    $output = $result->fetch_all(MYSQLI_ASSOC);
    $sresult = json_encode($output);
     
    echo $sresult;
?>


After doing all this in php and the html file this will be appear as follows: 
 

html




<!DOCTYPE html>
<html>
    <body>
        <h1 style = "color:#090; text-align:center;">neveropen</h1>
        <p style="font-size:25px">neveropen table values:</p>
 
 
         
        <p id="arrayContent"></p>
 
 
         
        <script>
        var obj, xmlhttp, myObj, x, txt = "";
        obj = JSON.stringify({"table":"neveropen"});
        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].names + "<br>";
                }
                document.getElementById("arrayContent").innerHTML = txt;
            }
        };
        xmlhttp.open("POST", "post.php", true);
        xmlhttp.setRequestHeader("Content-type",
                              "application/x-www-form-urlencoded");
        xmlhttp.send("x=" + obj );
         
        </script>
    </body>
</html>                   


Output: 
 

json post data

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments