AJAX - potatoscript/php GitHub Wiki
AJAX (Asynchronous JavaScript and XML) allows web pages to update content dynamically without reloading the entire page. This enhances user experience by making web applications faster and more interactive.
In this section, we will cover:
- What is AJAX?
- How AJAX Works in PHP
- Making an AJAX Request Using JavaScript (Vanilla JS)
- Using jQuery AJAX for Simplicity
- Handling AJAX Requests in PHP
- Working with JSON Responses
- AJAX CRUD Operations
AJAX allows the browser to send and retrieve data from the server in the background without refreshing the page. It is commonly used for:
- Form submission without reloading the page.
- Dynamic content loading (e.g., loading comments, user lists).
- Auto-search suggestions.
- Live chat systems.
AJAX follows these steps:
- A user interacts with a web page (e.g., clicks a button).
- JavaScript sends an HTTP request to a PHP script on the server.
- The PHP script processes the request and sends a response (usually in JSON format).
- JavaScript updates the web page based on the response.
HTML:
<input type="text" id="name" placeholder="Enter your name">
<button onclick="sendData()">Submit</button>
<p id="response"></p>
<script>
function sendData() {
var name = document.getElementById("name").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("response").innerHTML = xhr.responseText;
}
};
xhr.send("name=" + encodeURIComponent(name));
}
</script>
PHP (server.php
):
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'] ?? '';
echo "Hello, " . htmlspecialchars($name);
}
- The JavaScript function sends a
POST
request toserver.php
with the user's input. - The PHP script retrieves the data and returns a response.
- The response is displayed inside the
<p>
tag without refreshing the page.
jQuery makes AJAX much easier by providing the $.ajax()
method.
First, include jQuery in your project:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
HTML:
<input type="text" id="name" placeholder="Enter your name">
<button id="submit">Submit</button>
<p id="response"></p>
<script>
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
$.ajax({
type: "POST",
url: "server.php",
data: { name: name },
success: function(response) {
$("#response").html(response);
}
});
});
});
</script>
PHP (server.php
is the same as above).
- jQuery’s
$.ajax()
function simplifies sending data and handling the response. - No need to manually create
XMLHttpRequest
.
JSON (JavaScript Object Notation) is commonly used to exchange data between the client and server.
Modify server.php
:
header('Content-Type: application/json');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'] ?? 'Guest';
$response = ["message" => "Hello, " . htmlspecialchars($name)];
echo json_encode($response);
}
Modify JavaScript:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
$.ajax({
type: "POST",
url: "server.php",
data: { name: name },
dataType: "json",
success: function(response) {
$("#response").html(response.message);
}
});
});
});
-
header('Content-Type: application/json')
tells PHP to return JSON data. -
json_encode($response)
converts PHP data to JSON format. -
dataType: "json"
in jQuery automatically parses the response into an object.
A common use case of AJAX is performing Create, Read, Update, and Delete (CRUD) operations dynamically.
HTML:
<button id="loadData">Load Users</button>
<ul id="userList"></ul>
<script>
$(document).ready(function() {
$("#loadData").click(function() {
$.ajax({
url: "fetch_users.php",
method: "GET",
dataType: "json",
success: function(data) {
$("#userList").empty();
$.each(data, function(index, user) {
$("#userList").append("<li>" + user.name + "</li>");
});
}
});
});
});
</script>
PHP (fetch_users.php
):
header('Content-Type: application/json');
$users = [
["name" => "Alice"],
["name" => "Bob"],
["name" => "Charlie"]
];
echo json_encode($users);
- Clicking "Load Users" sends an AJAX request.
- The server responds with a JSON array of users.
- The client dynamically displays the users without refreshing the page.
To secure AJAX requests:
- Validate and sanitize input data in PHP.
- Use CSRF tokens to prevent cross-site request forgery.
- Restrict AJAX access to authenticated users when necessary.
Example: Basic Input Sanitization in PHP
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
Example: Restricting AJAX Access to Logged-in Users
session_start();
if (!isset($_SESSION['user_id'])) {
http_response_code(403);
echo json_encode(["error" => "Unauthorized"]);
exit;
}
In this section, we've covered:
- AJAX Basics: How AJAX works in PHP.
- Making AJAX Requests: Using JavaScript and jQuery.
- Working with JSON: Sending and receiving JSON data.
- AJAX CRUD Operations: Fetching data dynamically.
- Security Best Practices: Protecting AJAX requests.
AJAX improves user experience by making web applications more dynamic, reducing page reloads, and increasing efficiency. Using PHP with AJAX allows for real-time interactions, making applications feel smoother and more responsive.