This topic explains how a web page can consume data from a PHP REST API using JavaScript. The API acts as the backend data provider, and the frontend dynamically fetches and displays the data.
A REST API typically returns JSON data. JavaScript can request this data asynchronously using Fetch API or jQuery AJAX and then render it into HTML elements.
// Fetch data from PHP REST API and display it
<!DOCTYPE html>
<html>
<head>
<title>REST API Fetch Example</title>
</head>
<body>
<h3>Users List (from API)</h3>
<ul id="userList"></ul>
<script>
fetch("http://localhost/rest_api/read.php")
.then(response => response.json())
.then(data => {
let list = document.getElementById("userList");
data.forEach(user => {
let li = document.createElement("li");
li.textContent = user.name + " - " + user.email;
list.appendChild(li);
});
})
.catch(error => console.error("Error:", error));
</script>
</body>
</html>
// Use jQuery AJAX to consume REST API
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "http://localhost/rest_api/read.php",
method: "GET",
dataType: "json",
success: function(data) {
$.each(data, function(index, user){
$("#userList").append("<li>" + user.name + " - " + user.email + "</li>");
});
},
error: function() {
alert("Failed to fetch data from API");
}
});
});
</script>
// Sample JSON response returned by API
[
{ "id": 1, "name": "Alice", "email": "alice@example.com" },
{ "id": 2, "name": "Bob", "email": "bob@example.com" }
]
The API data is fetched asynchronously and each user record is appended to the HTML list dynamically without reloading the page.
catch()async/await for cleaner logic