AJAX with PHP
Connect JavaScript to PHP backend seamlessly
🔗 What is AJAX with PHP?
AJAX with PHP combines client-side JavaScript with server-side PHP to create interactive web applications. JavaScript sends requests to PHP scripts, which process data and return responses without page reloads.
// JavaScript sends request to PHP
fetch("process.php?name=John")
.then(response => response.text())
.then(data => console.log(data));
Output:
Hello John! Welcome to AJAX with PHP.
Key Concepts
AJAX with PHP enables real-time communication between browser and server. JavaScript handles user interactions and sends data to PHP, while PHP processes requests, interacts with databases, and returns formatted responses back to JavaScript.
Send Data
JavaScript sends to PHP
xhr.open("GET",
"script.php?id=5", true);
Process Data
PHP handles the request
$id = $_GET['id'];
echo "ID: $id";
Receive Response
JavaScript gets PHP output
xhr.onload = function() {
console.log(xhr.responseText);
};
Update Page
Display results dynamically
element.innerHTML =
xhr.responseText;
🔹 Simple AJAX-PHP Example
Basic communication between JavaScript and PHP:
🔸 HTML + JavaScript (index.html)
<!DOCTYPE html>
<html>
<body>
<button onclick="loadMessage()">Get Message</button>
<div id="result"></div>
<script>
function loadMessage() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "message.php", true);
xhr.onload = function() {
document.getElementById("result").innerHTML = xhr.responseText;
};
xhr.send();
}
</script>
</body>
</html>
🔸 PHP Script (message.php)
<?php
// Simple PHP response
echo "Hello from PHP! Current time: " . date("h:i:s A");
?>
Output:
Hello from PHP! Current time: 03:45:22 PM
🔹 Sending Data with GET
Pass parameters to PHP using GET method:
🔸 JavaScript
function getUserInfo() {
var username = document.getElementById("username").value;
var xhr = new XMLHttpRequest();
// Send data in URL
xhr.open("GET", "getuser.php?user=" + username, true);
xhr.onload = function() {
document.getElementById("info").innerHTML = xhr.responseText;
};
xhr.send();
}
🔸 PHP (getuser.php)
<?php
// Receive GET data
$username = $_GET['user'];
// Process and respond
if ($username == "john") {
echo "<p>Name: John Doe</p>";
echo "<p>Email: [email protected]</p>";
} else {
echo "<p>User not found!</p>";
}
?>
Output:
Name: John Doe
Email: [email protected]
🔹 Sending Data with POST
Send form data to PHP using POST method:
🔸 HTML + JavaScript
<input type="text" id="name" placeholder="Name">
<input type="email" id="email" placeholder="Email">
<button onclick="submitForm()">Submit</button>
<div id="response"></div>
<script>
function submitForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function() {
document.getElementById("response").innerHTML = xhr.responseText;
};
xhr.send("name=" + name + "&email=" + email);
}
</script>
🔸 PHP (submit.php)
<?php
// Receive POST data
$name = $_POST['name'];
$email = $_POST['email'];
// Validate and respond
if (!empty($name) && !empty($email)) {
echo "<p style='color: green;'>✓ Thank you, $name!</p>";
echo "<p>We'll contact you at $email</p>";
} else {
echo "<p style='color: red;'>✗ Please fill all fields!</p>";
}
?>
Output:
✓ Thank you, John!
We'll contact you at [email protected]
🔹 Returning JSON from PHP
Send structured data using JSON format:
🔸 JavaScript
fetch("getdata.php")
.then(response => response.json())
.then(data => {
console.log(data.name);
console.log(data.age);
console.log(data.city);
});
🔸 PHP (getdata.php)
<?php
// Create array
$data = array(
"name" => "John Doe",
"age" => 25,
"city" => "New York"
);
// Set JSON header
header("Content-Type: application/json");
// Return JSON
echo json_encode($data);
?>
Console Output:
25
New York
🔹 Live Search Example
Create a real-time search feature:
🔸 HTML + JavaScript
<input type="text" id="search" onkeyup="liveSearch()"
placeholder="Search...">
<div id="results"></div>
<script>
function liveSearch() {
var query = document.getElementById("search").value;
if (query.length == 0) {
document.getElementById("results").innerHTML = "";
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "search.php?q=" + query, true);
xhr.onload = function() {
document.getElementById("results").innerHTML = xhr.responseText;
};
xhr.send();
}
</script>
🔸 PHP (search.php)
<?php
$query = $_GET['q'];
$items = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
$results = array_filter($items, function($item) use ($query) {
return stripos($item, $query) !== false;
});
if (count($results) > 0) {
foreach ($results as $result) {
echo "<p>$result</p>";
}
} else {
echo "<p>No results found</p>";
}
?>
Output (typing "a"):
Apple
Banana
Date