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 sever 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 geeks.php

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<body>
<h1 style = "color:#090; text-align:center;">GeeksforGeeks</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", "geeks.php", true);
xmlhttp.send();
   
</script>
   
</body>
</html>

chevron_right


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”, “geeks.php”, true) function is used to get the value from the php file geeks.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”.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<body>
<h1 style = "color:#090; text-align:center;">GeeksforGeeks</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>  

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Now, extracting the data from other php script.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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


filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <body>
        <h1 style = "color:#090; text-align:center;">GeeksforGeeks</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>                    

chevron_right


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 are called by arrays and after printing the each myObj it’s values will be incremented to the next value.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <body>
        <h1 style = "color:#090; text-align:center;">GeeksforGeeks</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>        

chevron_right


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 beloe:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <body>
        <h1 style = "color:#090; text-align:center;">GeeksforGeeks</h1>
        <p style="font-size:25px">geeks table values:</p>
          
        <p id="arrayContent"></p>
          
        <script>
        var obj, xmlhttp, myObj, x, txt = "";
        obj = JSON.stringify({"table":"geeks"});
        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>                    

chevron_right


Output:
json post data



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.