Imagine 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 "user".
On the client, make a JSON object that describes the numbers of rows you want to return.
Before you send 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
Let's Learn
Step 1:
Create Index.php file and implement code as below
<h2 id="demo1"></h2>
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "root", "", "allphptricks");
$stmt = $conn->prepare("SELECT name FROM user LIMIT ?");
$stmt->bind_param("s", $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
<script>
var obj, dbParam, xmlhttp;
obj = { "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();
</script>
Loop Through the Result
Convert the result received from the PHP file into a JavaScript object, or in this case, a JavaScript array:
<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "limit":10 };
dbParam = JSON.stringify(obj);
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].name + "<br>";
}
document.getElementById("demo1").innerHTML = txt;
}
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();
</script>
<!DOCTYPE html>
<html>
<head>
<title>How To Get JSON Data From Data Base Using PHP File</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<br><br><br>
<div class="text-center">
<h1 id="color" style="color: tomato">How To Get JSON Data From Data Base Using PHP File In JavaScript</h1>
</div>
<br><br><br>
<div class="well">
<h2 id="demo1"></h2>
</div>
<script>
var obj, dbParam, xmlhttp;
obj = { "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</div>
</body>
</html>