Ajax and PHP work well together because they both run on different sides but support the same goal. They make websites faster and more responsive. You send and receive data without a full page reload.
Table of Content
This article shows you how to send requests and receive responses from the server using Ajax and PHP.
Understand What Ajax Is and How to Use It with PHP
The browser sends a request. The server gets it then runs code and sends back a result. Ajax helps this happen in the background while users stay on the same page.
Here are the common use cases of Ajax in web development:
- Search suggestions appear as you type
- Submit forms without page reload
- You update parts of a page after a button click
- Auto-refresh data like notifications
- Load more content without a full-page reload
You need a local server like XAMPP to test Ajax with PHP. You also need PHP and a modern browser.
Here is the basic file structure for Ajax + PHP projects:
- index.html or index.php
- script.js (for JavaScript)
- backend.php (for server-side code)
Let’s write the first Ajax request and connect it to a PHP file in the section below.
Write Your First Ajax Request
Use JavaScript to send a request:
This example sends a click request to the PHP file and shows the response.
HTML (index.html):
<button id="loadBtn">Load Message</button>
<div id="result"></div>
<script src="script.js"></script>
The button with id “loadBtn” triggers a JavaScript event when clicked. The result from the server shows inside the div with id “result”.
JavaScript (script.js):
document.getElementById('loadBtn').addEventListener('click', function () {
fetch('backend.php')
.then(response => response.text())
.then(data => {
document.getElementById('result').innerHTML = data;
});
});
The script sends a request to backend.php
when you click the button. It gets the response text and inserts it into the page inside the “result” div.
Create a simple PHP backend to handle the request:
This script returns a message string when called by JavaScript.
1- PHP (backend.php):
echo "Hello from PHP!";
2- Display the response in HTML:
The HTML above already has a placeholder div. JavaScript fills it with the server response.
Let’s move on to the following part to see how to handle form data with Ajax and PHP.
Handle Form Data with Ajax and PHP
Submit forms without page reload:
The form sends data to PHP. JavaScript catches the result and updates the page.
HTML Form:
<form id="userForm">
<input type="text" name="username" required>
<button type="submit">Submit</button>
</form>
<div id="formResult"></div>
This form collects a username and submits it when you click “Submit.”. The response from the server will appear inside the “formResult” div.
JavaScript (script.js):
document.getElementById('userForm').addEventListener('submit', function (e) {
e.preventDefault();
const formData = new FormData(this);
fetch('form_handler.php', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
document.getElementById('formResult').innerHTML = data;
});
});
It stops submitting normally and sends the data to form_handler.php
with POST. It takes the server’s response and shows it inside the “formResult” div.
Validate data with PHP:
This PHP file checks the input. It shows an error if it is empty.
PHP (form_handler.php):
$username = $_POST['username'] ?? '';
if (empty($username)) {
echo "Username is required.";
} else {
echo "Welcome, " . htmlspecialchars($username);
}
This script checks if the username
is empty and shows an error if it is. If not, it safely displays a welcome message using the submitted name.
Display server responses on the same page:
JavaScript already places the PHP message into the #formResult
div.
Work with JSON and PHP in Ajax
Send JSON Data to PHP:
This example sends a user object to PHP using fetch and JSON.
JavaScript:
const user = { name: "Alice", age: 25 };
fetch('json_handler.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(data => {
console.log(data);
});
It sends a JSON object with name and age to json_handler.php
using POST.
The server responds with JSON, and the result is logged to the console.
Encoding and decoding JSON in PHP:
PHP reads the JSON, builds a message, and returns it.
PHP (json_handler.php):
$input = json_decode(file_get_contents("php://input"), true);
$name = $input['name'] ?? '';
$age = $input['age'] ?? '';
$response = [
'message' => "User: $name, Age: $age"
];
header('Content-Type: application/json');
echo json_encode($response);
It reads and decodes the JSON input sent from JavaScript. Then it builds a response message and sends it back as JSON.
Use JSON responses to update the DOM dynamically:
After you receive the message
in JavaScript, you can insert it into the page using innerHTML
or any DOM method.
You will now see how to use jQuery for Ajax to make things shorter and simpler.
Use jQuery Ajax with PHP
Benefits of jQuery for Ajax:
jQuery handles browser issues. It makes Ajax calls shorter. It works well with older and newer browsers.
Write Ajax Calls with $.ajax(), $.get(), and $.post():
This example sends a GET request when you click the button.
HTML:
<button id="loadBtn2">Load via jQuery</button>
<div id="result2"></div>
jQuery Script:
$('#loadBtn2').click(function () {
$.get('backend.php', function (data) {
$('#result2').html(data);
});
});
It sends a GET request to backend.php
when you click the button. The server’s response is placed inside the “result2” div.
Handle success and error events:
This adds success and error checks using $.ajax.
$.ajax({
url: 'backend.php',
method: 'GET',
success: function (data) {
$('#result2').html(data);
},
error: function () {
$('#result2').html('Request failed.');
}
});
It sends a GET request to backend.php
and shows the response in the “result2” div. It shows an error message instead if the request fails.
Let’s now look at real examples that show how Ajax and PHP work together.
Ajax and PHP Examples
Live search (As the user types):
Use keyup
to detect typing. Send text to the server. PHP returns matches.
JavaScript:
document.getElementById('search').addEventListener('keyup', function () {
const query = this.value;
fetch('search.php?q=' + query)
.then(response => response.text())
.then(data => {
document.getElementById('results').innerHTML = data;
});
});
It sends the typed search query to search.php
after each key press.
The server returns results, which are shown in the “results” div.
PHP (search.php):
$q = $_GET['q'] ?? '';
echo "Results for: " . htmlspecialchars($q);
It gets the search query from the URL using $_GET['q']
. Then it safely displays the result with htmlspecialchars()
to prevent XSS.
Auto-refreshing content (Chat Messages):
Use setInterval to fetch data every few seconds. Update the chat box.
setInterval(function () {
fetch('messages.php')
.then(response => response.text())
.then(data => {
document.getElementById('chatBox').innerHTML = data;
});
}, 3000);
This example fetches new data from messages.php
every 3 seconds.
The latest messages replace the content inside the “chatBox” div.
Dependent dropdowns (country > state > city):
It fetches data to update the next one when one dropdown changes.
document.getElementById('country').addEventListener('change', function () {
fetch('states.php?country=' + this.value)
.then(response => response.text())
.then(data => {
document.getElementById('state').innerHTML = data;
});
});
It sends the value to states.php
when the user selects a country. The response updates the “state” dropdown with matching options.
Load more button (infinite scroll):
Click the button. Fetch the next page and add it to the list.
document.getElementById('loadMore').addEventListener('click', function () {
fetch('more.php?page=2')
.then(response => response.text())
.then(data => {
document.getElementById('list').innerHTML += data;
});
});
It fetches more content from more.php
when the “Load More” button is clicked. The new data is added to the existing list without reloading the page.
Let’s move on to the following part to see security considerations with examples in Ajax and PHP.
Security Considerations
Protect against SQL injection and XSS:
Use prepared statements in SQL. Escape HTML output to stop script injection.
Validate and sanitize user input in PHP:
Use filter_input()
and htmlspecialchars()
. Never trust raw input.
Use CSRF tokens with Ajax:
Add a CSRF token to your Ajax request. Match it on the server before doing anything else.
You now reached the end. Let’s close with a summary.
Wrapping Up
In this article, you learned how Ajax helps PHP apps send and receive data in the background. You also saw how to send form data, handle JSON, use jQuery, and stay secure.
Here is a quick recap:
- Ajax updates pages without reload
- You can send form data or JSON
- PHP handles requests and returns responses
- jQuery makes Ajax shorter
- Always validate and secure your data