This chapter will teach you how to exchcange JSON data between the client and a PHP server.
The PHP File
PHP has some built-in functions to handle JSON.
objegt in PHP can be converted into JSON by using the PHP function json_encode().
PHP Database
PHP is a server side programming language, and should be used for operations that can only be performed by a server, like accessing a database. imaging you have a database on the server, containing customers, products, and suppliers.
you want to make a request to the srever where you ask for the first 10 records in the customers table:
<!DOCTYPE html>
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p>The JSON received from the PHP file:</p>
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp;
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</body>
</html>
Example explained:
1. Define an object containing a table property and a limit property.
2. Convert the object ito a JSON string.
3. Send a request to the PHP file, with the JSON string as a parameter.
4. Wait until the request returns with the result (as JSON)
5. Display the result received from the PHP file.
Take a look at the PHP file.
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM ".$obj->table." LIMIT ".$obj->limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM ".$obj->table." LIMIT ".$obj->limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
PHP File explained:
- Convert the request into an object, using PHP function json_decode().
- Access the database, and fill an arrary with the requested data.
- Add the array to an object, and return the objectg as JSON using the json_encode() function.
No comments:
Post a Comment