-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
JavaScript AJAX with PHP is one of the most important concepts in modern web development. It allows a web page to communicate with the server without reloading, making websites faster, smoother, and more user-friendly. Features like live search, form submission, pagination, chat systems, and real-time updates are all built using AJAX.
In this tutorial, you will learn what AJAX is, how JavaScript AJAX works with PHP, request and response flow, GET and POST requests, practical examples, common use cases, and best practices. Everything is explained step by step in simple and practical language.
AJAX stands for Asynchronous JavaScript and XML. Despite the name, AJAX does not require XML. Today, JSON and plain text are more commonly used.
AJAX allows JavaScript to send requests to the server and receive responses in the background, without refreshing the web page.
This means:
The page stays loaded
Only required data is updated
User experience feels faster and smoother
PHP is a server-side language, and JavaScript runs in the browser. AJAX connects these two.
Using JavaScript AJAX with PHP allows you to:
Submit forms without page reload
Fetch data from the database dynamically
Implement live search
Build pagination systems
Create login and registration systems
Update content in real time
AJAX acts as a bridge between frontend and backend.
The basic working flow is simple:
User performs an action in the browser
JavaScript sends a request to the PHP file
PHP processes the request on the server
PHP returns a response
JavaScript updates the page dynamically
This entire process happens without refreshing the page.
AJAX mainly uses two HTTP methods:
GET
POST
GET is used to fetch data
POST is used to send data securely
Both methods are commonly used with PHP.
AJAX requests are commonly created using the XMLHttpRequest object.
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.send();
This sends a request to a PHP file named data.php.
To read the response from PHP:
xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
responseText contains the data returned by PHP.
<button onclick="loadData()">Load Data</button>
<div id="output"></div>
<script>
function loadData() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onload = function () {
if (xhr.status === 200) {
document.getElementById("output").innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
<?php
echo "Hello from PHP using AJAX";
?>
When the button is clicked, data is loaded without refreshing the page.
let xhr = new XMLHttpRequest();
xhr.open("GET", "user.php?name=Rahul", true);
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
<?php
$name = $_GET['name'];
echo "Welcome " . $name;
?>
This sends data from JavaScript to PHP using a GET request.
POST requests are more secure and widely used for forms.
let xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send("username=admin&password=1234");
<?php
$username = $_POST['username'];
$password = $_POST['password'];
echo "Username: " . $username;
?>
POST is preferred when sending sensitive data.
<form id="myForm">
<input type="text" name="email">
<button type="submit">Submit</button>
</form>
<div id="message"></div>
document.getElementById("myForm").addEventListener("submit", function (e) {
e.preventDefault();
let formData = new FormData(this);
let xhr = new XMLHttpRequest();
xhr.open("POST", "form.php", true);
xhr.onload = function () {
document.getElementById("message").innerHTML = xhr.responseText;
};
xhr.send(formData);
});
<?php
$email = $_POST['email'];
echo "Email received: " . $email;
?>
This is a real-world example of form submission using AJAX.
let xhr = new XMLHttpRequest();
xhr.open("GET", "users.php", true);
xhr.onload = function () {
document.getElementById("output").innerHTML = xhr.responseText;
};
xhr.send();
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
$result = mysqli_query($conn, "SELECT name FROM users");
while ($row = mysqli_fetch_assoc($result)) {
echo "<p>" . $row['name'] . "</p>";
}
?>
This dynamically loads data from the database.
Always handle errors to improve reliability.
xhr.onerror = function () {
console.log("Request failed");
};
Checking status codes helps avoid unexpected behavior.
PHP can return data in different formats:
Plain text
HTML
JSON
JSON is the most popular format.
<?php
$data = ["name" => "Amit", "age" => 25];
echo json_encode($data);
?>
let data = JSON.parse(xhr.responseText);
console.log(data.name);
JavaScript AJAX with PHP is used for:
Live search
Login and registration
Infinite scrolling
Dynamic pagination
Contact forms
Chat applications
Admin dashboards
Almost every dynamic website uses AJAX.
Forgetting to check request status
Not sanitizing data in PHP
Using GET for sensitive data
Ignoring error handling
Reloading page unnecessarily
Avoiding these mistakes improves performance and security.
Validate data on both client and server
Use POST for sensitive information
Return JSON for structured data
Keep PHP logic clean and secure
Show loading indicators for better UX
Handle failures gracefully
Following best practices results in professional-quality applications.
Sanitize input using PHP functions
Protect against SQL injection
Avoid exposing sensitive server logic
Use HTTPS
Never trust client-side data blindly
Security is critical when using AJAX with PHP.
JavaScript AJAX with PHP allows web applications to communicate with the server without refreshing the page. By combining JavaScript on the frontend and PHP on the backend, you can build fast, interactive, and modern web applications. From simple data fetching to complex systems like live search and form handling, AJAX plays a key role in improving user experience. Understanding how requests, responses, methods, and security work together will help you build scalable and professional web applications with confidence.
Write an AJAX GET request to fetch a greeting from greet.php and display it in a <div> when a button is clicked.
Create a form with an input field for a name and send it via AJAX POST to process.php, then display the server response.
Fetch JSON data from user.php and display Sanjana’s name, age, and email dynamically on the page.
Write an AJAX request that handles errors when process.php is missing (404) and shows an alert.
Create a button that sends a name to PHP via POST and updates a <p> element with the returned message.
Fetch an HTML snippet from snippet.php and insert it into a <div> without reloading the page.
Send multiple form fields (name, email, age) via AJAX POST to PHP and display a confirmation message.
Write code to fetch JSON from user.php, parse it, and populate an unordered list <ul> with the data.
Create an AJAX request that times out after 5 seconds and shows an error message if PHP doesn’t respond.
Write a function that sends the user’s name to PHP, receives a personalized greeting, and appends it to a <div> each time the button is clicked.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
