JSON PHP

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

JSON PHP

JSON is used to read data from a web server and display the data on a web page.

The PHP File

PHP consists of some built-in functions to handle JSON.

Objects in PHP can be converted into JSON by using the PHP function json_encode().

PHP file

<?php

$myObj = new stdClass();

$myObj->name = “John”;

$myObj->age = 30;

$myObj->city = “New York”;

$myJSON = json_encode($myObj);

echo $myJSON;

?>

The Client JavaScript

We’ll be using an AJAX call to request the PHP file from the example above:

Example

<!DOCTYPE html>

<html>

<body>

<h2>Get JSON Data from a PHP Server</h2>

<p id=”demo”></p>

<script>

const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {

  const myObj = JSON.parse(this.responseText);

  document.getElementById(“demo”).innerHTML = myObj.name;

}

xmlhttp.open(“GET”, “demo_file.php”);

xmlhttp.send();

</script>

</body>

</html>

Output

Get JSON Data from a PHP Server

John

PHP Array

Arrays in PHP is converted into JSON when using the PHP function json_encode().

PHP file

<?php

$myArr = array(“John”, “Mary”, “Peter”, “Sally”);

$myJSON = json_encode($myArr);

echo $myJSON;

?>

The Client JavaScript

We’ll be using an AJAX call to request the PHP file from the array example above.

Example

<!DOCTYPE html>

<html>

<body>

<h2>Get JSON Data from a PHP Server</h2>

<p>Convert the data into a JavaScript array:</p>

<p id=”demo”></p>

<script>

const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {

  const myObj = JSON.parse(this.responseText);  document.getElementById(“demo”).innerHTML = myObj[2];

}

xmlhttp.open(“GET”, “demo_file_array.php”);

xmlhttp.send();

</script>

</body>

</html>

Output

Get JSON Data from a PHP Server

Convert the data into a JavaScript array:

Peter

PHP Database

PHP is a server-side programming language and can be used to access a database.

Let’s suppose you have a database on your server, and you want to send a request to it from the client where you ask for the 10 first rows in a table called “customers”.

On the client, make a JSON object that defines the number of rows you want to return.

Before sending the request to the server, convert the JSON object into a string and send it as a parameter to the URL of the PHP page.

Example

<!DOCTYPE html>

<html>

<body>

<h2>Get JSON Data from a PHP Server</h2>

<p>The JSON received from the PHP file:</p>

<p id=”demo”></p>

<script>

const dbParam = JSON.stringify({“limit”:10});

const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {

 document.getElementById(“demo”).innerHTML = this.responseText;

}

xmlhttp.open(“GET”, “json_demo_db.php?x=” + dbParam);

xmlhttp.send();

</script>

</body>

</html>

Output

Get JSON Data from a PHP Server

The JSON received from the PHP file:

[{"name":"Alfreds Futterkiste"},{"name":"Ana Trujillo Emparedados y helados"},{"name":"Antonio Moreno Taqueria"},{"name":"Around the Horn"},{"name":"Berglunds snabbkop"},{"name":"Blauer See Delikatessen"},{"name":"Blondel pere et fils"},{"name":"Bolido Comidas preparadas"},{"name":"Bon app'"},{"name":"Bottom-Dollar Marketse"}]

Example explained

Define an object consisting of a “limit” property and value.

Convert the object into a JSON string.

Sending a request to the PHP file, with the JSON string as a parameter.

Wait until the request returns with the result (as JSON)

Show the result received from the PHP file.

Take a look at the PHP file:

Example

<?php

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

$obj = json_decode($_GET[“x”], false);

$conn = new mysqli(“myServer”, “myUser”, “myPassword”, “Northwind”);

$stmt = $conn->prepare(“SELECT name FROM customers LIMIT ?”);

$stmt->bind_param(“s”, $obj->limit);

$stmt->execute();

$result = $stmt->get_result();

$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp);

?>

PHP File explained

Convert the request into an object, with PHP function json_decode().

Access the database, and fill an array using the requested data.

Add the array to an object, and return the object as with json_encode() function.

Use the Data

Example

<!DOCTYPE html>

<html>

<body>

<h2>Get JSON Data from a PHP Server</h2>

<p id=”demo”></p>

<script>

const obj = { “limit”:10 };

const dbParam = JSON.stringify(obj);

const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {

  myObj = JSON.parse(this.responseText);

  let text = “”

  for (let x in myObj) {

    text += myObj[x].name + “<br>”;

  }  document.getElementById(“demo”).innerHTML = text;

};

xmlhttp.open(“GET”, “json_demo_db.php?x=” + dbParam);

xmlhttp.send();

</script>

</body>

</html>

Output

Get JSON Data from a PHP Server

Alfreds Futterkiste

Ana Trujillo Emparedados y helado

Antonio Moreno Taqueria

Around the Horn

Berglunds snabbkop

Blauer See Delikatessen

Blondel pere et fils

Bolido Comidas preparadas

Bon app'

Bottom-Dollar Marketse

PHP Method = POST

While sending data to the server, use the HTTP POST method.

To send AJAX requests using the POST method, define the method, and the correct header.

The data sent to the server must now be an argument to the send() method:

Example

<!DOCTYPE html>

<html>

<body>

<h2>Use HTTP POST to Get JSON Data from a PHP Server</h2>

<p id=”demo”></p>

<script>

const dbParam = JSON.stringify({“limit”:10});

const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {

  myObj = JSON.parse(this.responseText);

  let text = “”;

  for (let x in myObj) {

    text += myObj[x].name + “<br>”;

  }

document.getElementById(“demo”).innerHTML = text;

}

xmlhttp.open(“POST”, “json_demo_db_post.php”);

xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);

xmlhttp.send(“x=” + dbParam);

</script>

</body>

</html>

Output

Use HTTP POST to Get JSON Data from a PHP Server

Alfreds Futterkiste

Ana Trujillo Emparedados y helado

Antonio Moreno Taqueria

Around the Horn

Berglunds snabbkop

Blauer See Delikatessen

Blondel pere et fils

Bolido Comidas preparadas

Bon app'

Bottom-Dollar Marketse

The only difference in the PHP file is the method for getting the transferred data.

PHP file

Example

<?php

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

$obj = json_decode($_POST[“x”], false);

$conn = new mysqli(“myServer”, “myUser”, “myPassword”, “Northwind”);

$stmt = $conn->prepare(“SELECT name FROM customers LIMIT ?”);

$stmt->bind_param(“s”, $obj->limit);

$stmt->execute();

$result = $stmt->get_result();

$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp);

?>