AJAX with PHP
Connecting AJAX to PHP backend
🐘 What is AJAX with PHP?
AJAX with PHP enables dynamic communication between your webpage and PHP server scripts. You can send data to PHP, process it server-side, and receive responses without page reloads, creating interactive applications.
// Send request to PHP
xhr.open('GET', 'process.php', true);
xhr.send();
AJAX + PHP Features
Database Access
Query databases from PHP scripts
mysqli_query($conn, $sql)
Server Processing
Handle logic securely on server
$_POST['username']
Data Validation
Validate input before processing
filter_var($email, FILTER_VALIDATE_EMAIL)
Dynamic Content
Generate content based on requests
echo json_encode($data)
🔹 Simple PHP Script
PHP scripts process AJAX requests and return responses. This basic example shows how PHP receives and responds to AJAX calls.
<?php
// Simple PHP response script (response.php)
// Get data from AJAX request
$name = $_GET['name'];
// Process and respond
if ($name) {
echo "Hello, " . $name . "!";
} else {
echo "Hello, Guest!";
}
?>
PHP Output:
Hello, John!
🔹 AJAX GET Request to PHP
GET requests send data through URL parameters to PHP scripts. This method is simple and ideal for retrieving data from servers.
<!DOCTYPE html>
<html>
<body>
<h2>Get User Info</h2>
<input type="text" id="username" placeholder="Enter name">
<button onclick="getInfo()">Get Info</button>
<div id="result"></div>
<script>
function getInfo() {
const name = document.getElementById('username').value;
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('result').innerHTML = xhr.responseText;
}
};
// Send GET request with parameter
xhr.open('GET', 'getuser.php?name=' + name, true);
xhr.send();
}
</script>
</body>
</html>
<?php
// getuser.php
$name = $_GET['name'];
echo "<h3>Welcome, " . htmlspecialchars($name) . "!</h3>";
echo "<p>Your account is active.</p>";
?>
🔹 AJAX POST Request to PHP
POST requests send data in the request body, making them more secure for sensitive information. PHP accesses this data through the $_POST superglobal.
<!DOCTYPE html>
<html>
<body>
<h2>User Registration</h2>
<input type="text" id="username" placeholder="Username">
<input type="email" id="email" placeholder="Email">
<button onclick="register()">Register</button>
<div id="message"></div>
<script>
function register() {
const username = document.getElementById('username').value;
const email = document.getElementById('email').value;
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('message').innerHTML = xhr.responseText;
}
};
xhr.open('POST', 'register.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Send POST data
xhr.send('username=' + username + '&email=' + email);
}
</script>
</body>
</html>
<?php
// register.php
$username = $_POST['username'];
$email = $_POST['email'];
// Validate data
if (empty($username) || empty($email)) {
echo "❌ Please fill all fields!";
} else {
// Process registration (save to database, etc.)
echo "✅ Registration successful!";
echo "<br>Username: " . htmlspecialchars($username);
echo "<br>Email: " . htmlspecialchars($email);
}
?>
🔹 PHP with JSON Response
Modern applications use JSON for data exchange between AJAX and PHP. JSON provides a structured, easy-to-parse format for complex data.
// JavaScript - Send request
function loadUser() {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
// Parse JSON response
const user = JSON.parse(xhr.responseText);
document.getElementById('output').innerHTML =
'<h3>' + user.name + '</h3>' +
'<p>Email: ' + user.email + '</p>' +
'<p>Age: ' + user.age + '</p>';
}
};
xhr.open('GET', 'getuser.php?id=1', true);
xhr.send();
}
<?php
// getuser.php - Return JSON
header('Content-Type: application/json');
$id = $_GET['id'];
// Simulate database query
$user = array(
'id' => $id,
'name' => 'John Doe',
'email' => '[email protected]',
'age' => 30
);
// Return JSON
echo json_encode($user);
?>
🔹 PHP Database Example
AJAX with PHP commonly interacts with databases. This example demonstrates fetching user data from a MySQL database and returning it as JSON.
<?php
// database.php - Fetch from database
header('Content-Type: application/json');
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die(json_encode(['error' => 'Connection failed']));
}
// Query database
$sql = "SELECT id, name, email FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
echo json_encode($row);
} else {
echo json_encode(['error' => 'User not found']);
}
$conn->close();
?>
Security Tips:
- Use prepared statements to prevent SQL injection
- Validate input before processing
- Sanitize output with htmlspecialchars()
- Set proper headers for JSON responses
🔹 Complete AJAX-PHP Example
Here's a full working example showing a search feature that queries PHP and displays results dynamically:
<!DOCTYPE html>
<html>
<body>
<h2>User Search</h2>
<input type="text" id="search" onkeyup="searchUser()" placeholder="Search users...">
<div id="results"></div>
<script>
function searchUser() {
const query = document.getElementById('search').value;
if (query.length === 0) {
document.getElementById('results').innerHTML = '';
return;
}
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('results').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'search.php?q=' + query, true);
xhr.send();
}
</script>
</body>
</html>
<?php
// search.php
$query = $_GET['q'];
// Sample data (in real app, query database)
$users = array(
'John Doe',
'Jane Smith',
'Bob Johnson',
'Alice Williams'
);
// Filter results
$results = array_filter($users, function($user) use ($query) {
return stripos($user, $query) !== false;
});
// Display results
if (count($results) > 0) {
echo "<ul>";
foreach ($results as $user) {
echo "<li>" . htmlspecialchars($user) . "</li>";
}
echo "</ul>";
} else {
echo "<p>No results found.</p>";
}
?>