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 geeks.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;" >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 >
|
Output:

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”.
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;" >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 >
|
Output:

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" , "" , "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();
?>
|
Now, extracting the data from other php script.
php
<?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();
?>
|
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;" >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 >
|
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:

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;" >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 >
|
Output:

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" , "" , "geeksforgeeks" );
$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;" >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 >
|
Output:

Similar Reads
JavaScript JSONP
What is JSONP?The **XMLHttpRequest (XHR)** is a tool used to retrieve data from a server. Once the data is received by the browser, it can be converted from a JSON string into a JavaScript object using the `JSON.parse()` method. However, XHR encounters an issue known as the **same-origin policy**. T
4 min read
JavaScript JSON
JSON (JavaScript Object Notation) is a lightweight data format for storing and exchanging data. It is widely used to send data between a server and a client. JSON is simple, language-independent, and easy to understand. JSON stands for JavaScript Object Notation.It is a lightweight, text-based data
5 min read
JavaScript JSON Parser
JSON (JavaScript Object Notation) is a popular lightweight data exchange format for sending data between a server and a client, or across various systems. JSON data is parsed and interpreted using a software component or library called a JSON parser. Through the JSON parsing process, a JSON string i
3 min read
JavaScript JSON parse() Method
The JSON.parse() method is used to convert a JSON string into a JavaScript object. Itâs become important when dealing with data in JSON format, interacting with APIs, or storing data in the browser. It converts a JSON string into a JavaScript object.Throws a SyntaxError if the input string is not va
4 min read
JavaScript | JSON Arrays
The JSON Arrays is similar to JavaScript Arrays. Syntax of Arrays in JSON Objects: // JSON Arrays Syntax { "name":"Peter parker", "heroName": "Spiderman", "friends" : ["Deadpool", "Hulk", "Wolverine"] } Accessing Array Values: The Array values can be accessed using the index of each element in an Ar
2 min read
JSON vs JavaScript Object
JSON (JavaScript Object Notation) and JavaScript Objects are important for handling data in JavaScript, but they serve different purposes. JSON is a lightweight data format for transferring data, while JavaScript Objects are in-program data structures used for manipulation and logic. What is JSON?JS
3 min read
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipula
2 min read
How to Master JSON in JavaScript?
JSON is a text format for representing structured data, typically in the form of key-value pairs. It primarily sends data between a server and a client, especially in web APIs. Objects are enclosed in curly braces {} and contain key-value pairs.Arrays are enclosed in square brackets [] and hold valu
5 min read
How to Parse JSON Data in JavaScript?
To parse JSON data in JavaScript, you can use the JSON.parse() method. This method converts a JSON string into a JavaScript object, making it easier to work with the data. 1. Parse Simple JSON Strings[GFGTABS] JavaScript //Driver Code Starts{ const jsonS = '{"name": "Rahul",
2 min read
JavaScript JSON Complete Reference
JavaScript JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It is easy to read, write, and parse. JSON is based on key-value pairs and arrays. [GFGTABS] JavaScript let data = '{"name":"Raj","age":25}'; let obj = JSON.par
1 min read