AJAXÂ PHP
15 April 2025 | Category: JavaScript
AJAX allows you to send and receive data from a PHP server without reloading the page. It helps in creating dynamic and responsive web applications.
đ What We’ll Learn
- Sending data from JavaScript to PHP using AJAX
- Receiving server response and displaying it on the page
- A real-world example: username availability checker
đ Project Files Structure
ajax-php/
â
âââ index.html â HTML file with JavaScript
âââ server.php â PHP file that processes the request
đ§± 1. index.html
â Frontend with AJAX
<!DOCTYPE html>
<html>
<head>
<title>AJAX with PHP Example</title>
</head>
<body>
<h2>Check Username</h2>
<input type="text" id="username" placeholder="Enter username" onkeyup="checkUsername()">
<p id="result"></p>
<script>
function checkUsername() {
const username = document.getElementById("username").value;
const xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function () {
if (xhr.status === 200) {
document.getElementById("result").innerText = xhr.responseText;
}
};
xhr.send("username=" + encodeURIComponent(username));
}
</script>
</body>
</html>
đ„ïž 2. server.php
â Backend PHP Script
<?php
if (isset($_POST['username'])) {
$username = $_POST['username'];
// Dummy usernames already taken
$taken_usernames = ['admin', 'user', 'test'];
if (in_array(strtolower($username), $taken_usernames)) {
echo "â Username already taken";
} else if ($username == "") {
echo "";
} else {
echo "â
Username is available";
}
}
?>
đ How it Works
- You type in the input field.
- JavaScript captures the value on every key press (
onkeyup
). - AJAX sends a POST request to
server.php
. - PHP script checks if the username is taken and sends back a message.
- JavaScript updates the page with the response.
â Output (Live Feedback)
Input: admin â â Username already taken
Input: yourname â â
Username is available
đ Security Tip
- Always sanitize input in PHP using
htmlspecialchars()
,filter_input()
, or validation libraries. - Use AJAX to enhance UX, but validate data on server side too.
đ§ Summary
- AJAX lets JavaScript communicate with PHP in the background.
- You can send data using GET or POST.
- PHP processes and sends a response, which JavaScript uses to update the UI.
- Great for login systems, form validation, search suggestions, etc.