-
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
AJAX allows web pages to communicate with the server without reloading, and PHP is one of the most popular server-side languages. Using AJAX with PHP lets you fetch or send data dynamically, making your web applications more interactive.
AJAX PHP refers to using AJAX requests in JavaScript to interact with PHP scripts on the server. This combination is widely used for tasks like:
Submitting forms without refreshing the page.
Loading data from a database dynamically.
Displaying filtered content based on user input.
AJAX handles the client-side communication, while PHP handles the server-side processing.
Imagine you want to fetch a greeting message from the server using PHP.
greet.php
)<?php
// Set content type to plain text
header('Content-Type: text/plain');
// Send a greeting message
echo "Hello, Sanjana! Welcome to AJAX with PHP.";
?>
<button id="loadBtn">Get Greeting</button>
<div id="output"></div>
<script>
document.getElementById("loadBtn").addEventListener("click", function() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "greet.php", true); // Initialize GET request
xhr.onload = function() {
if (xhr.status === 200) {
// Display server response in the div
document.getElementById("output").textContent = xhr.responseText;
} else {
document.getElementById("output").textContent = "Error loading message";
}
};
xhr.send(); // Send the request
});
</script>
Explanation:
The PHP script generates a plain text response.
The AJAX request fetches it asynchronously.
xhr.responseText
contains the server’s response.
Clicking the button will display:
“Hello, Sanjana! Welcome to AJAX with PHP.”
AJAX can also send data to PHP for processing using the POST method.
<input type="text" id="username" placeholder="Enter your name">
<button id="sendBtn">Send</button>
<div id="response"></div>
document.getElementById("sendBtn").addEventListener("click", function() {
let name = document.getElementById("username").value;
let xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
// Set header for form data
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById("response").textContent = xhr.responseText;
} else {
document.getElementById("response").textContent = "Error sending data";
}
};
// Send data to PHP
xhr.send("username=" + encodeURIComponent(name));
});
process.php
)<?php
if(isset($_POST['username'])){
$name = htmlspecialchars($_POST['username']); // Sanitize input
echo "Hello, $name! Your data has been received by PHP.";
} else {
echo "No data received.";
}
?>
Explanation:
Data from the input field is sent via POST
.
encodeURIComponent()
ensures special characters are handled correctly.
PHP retrieves the data with $_POST['username']
.
htmlspecialchars()
prevents XSS attacks.
If Sanjana enters her name, the response will be:
“Hello, Sanjana! Your data has been received by PHP.”
AJAX PHP is often used to retrieve JSON data from the server, especially when working with databases.
user.php
)<?php
header('Content-Type: application/json');
$user = array(
"name" => "Sanjana",
"age" => 26,
"email" => "sanjana@example.com"
);
echo json_encode($user);
?>
let xhr = new XMLHttpRequest();
xhr.open("GET", "user.php", true);
xhr.onload = function() {
if (xhr.status === 200) {
let user = JSON.parse(xhr.responseText); // Convert JSON string to object
document.getElementById("output").innerHTML =
`Name: ${user.name}<br>Age: ${user.age}<br>Email: ${user.email}`;
} else {
document.getElementById("output").textContent = "Failed to load data";
}
};
xhr.send();
Explanation:
json_encode()
converts the PHP array into a JSON string.
JSON.parse()
converts it back into a JavaScript object.
This makes it easy to dynamically display user information.
Always check the status code to ensure your AJAX request succeeds.
xhr.onload = function() {
if (xhr.status === 200) {
console.log("Request successful:", xhr.responseText);
} else if (xhr.status === 404) {
console.error("PHP file not found.");
} else {
console.error("Server error:", xhr.status);
}
};
200
indicates success.
404
means the file is missing.
Other codes indicate server errors.
AJAX PHP allows you to:
Fetch data from the server dynamically without page reload.
Send form or user data to PHP for processing.
Receive plain text, HTML, or JSON responses.
Handle errors using HTTP status codes.
Build interactive applications like dynamic forms, live search, and content updates.
By combining AJAX and PHP, you can create responsive web applications that are more user-friendly and efficient.
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