-
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
An AJAX request is the process of sending a message to a web server and receiving a response without reloading the page. It allows websites to fetch or send data in the background, making the user experience smooth and interactive.
AJAX requests can be made using XMLHttpRequest or the modern Fetch API, but understanding the request process is key to building dynamic web applications.
An AJAX request consists of three main parts:
Request initiation – The client (browser) tells the server it wants data.
Server processing – The server processes the request and prepares a response.
Response handling – The client receives the data and updates the page dynamically.
Requests can be GET or POST, and they can send or receive text, JSON, HTML, or XML data.
The XMLHttpRequest object is used to create AJAX requests.
// Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();
// Define the function to handle the server response
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText); // Log the response text
}
};
// Initialize a GET request
xhr.open("GET", "data.txt", true);
// Send the request to the server
xhr.send();
xhr.open("GET", "data.txt", true)
prepares a GET request to data.txt
.
true
makes it asynchronous so the page doesn’t freeze.
xhr.send()
sends the request.
xhr.onreadystatechange
runs whenever the readyState
changes.
When readyState
is 4
and status
is 200
, the response is ready and successful.
GET Request: Retrieves data from the server. Parameters are sent in the URL.
xhr.open("GET", "server.php?user=Vicky", true);
xhr.send();
POST Request: Sends data to the server. Parameters are sent in the request body.
xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("user=Vicky&age=28");
Key Differences:
GET is visible in the URL; POST is hidden in the request body.
POST can send larger amounts of data.
GET is generally faster and can be cached; POST is used for sensitive or large data.
AJAX responses can be of different types:
Text: Plain text content from a server.
HTML: A snippet of HTML code to be inserted into a page.
JSON: Structured data used in modern web applications.
let xhr = new XMLHttpRequest();
xhr.open("GET", "user.json", true);
xhr.onload = function() {
if (xhr.status === 200) {
let user = JSON.parse(xhr.responseText); // Convert JSON to JS object
console.log("User Name:", user.name);
console.log("User Age:", user.age);
}
};
xhr.send();
Here, JSON.parse()
converts the JSON string from the server into a JavaScript object.
Headers provide additional information to the server. For example, when sending JSON data:
let xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
let data = { name: "Vicky", age: 28 };
xhr.send(JSON.stringify(data));
Explanation:
setRequestHeader()
specifies that the request body is JSON.
JSON.stringify(data)
converts a JavaScript object to a JSON string for sending.
It is important to handle errors properly in AJAX requests.
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("Request Successful:", xhr.responseText);
} else if (xhr.status === 404) {
console.error("Error 404: File not found");
} else {
console.error("Error:", xhr.status);
}
}
};
This ensures your web application can react gracefully if something goes wrong.
<button id="loadBtn">Load Data</button>
<div id="result"></div>
<script>
document.getElementById("loadBtn").addEventListener("click", function() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById("result").textContent = xhr.responseText;
} else {
document.getElementById("result").textContent = "Failed to load data";
}
};
xhr.send();
});
</script>
Explanation:
Fetches data from data.txt
.
Displays it in a <div>
with id result
.
The page doesn’t reload.
AJAX requests can also include options like timeout or credentials.
xhr.timeout = 5000; // Timeout in milliseconds
xhr.ontimeout = function() {
console.error("Request timed out");
};
xhr.withCredentials = true; // Include cookies if needed
This makes AJAX requests more robust and secure.
An AJAX request is the core of modern interactive websites. Using XMLHttpRequest, you can send or fetch data asynchronously, handle JSON, HTML, or text responses, set headers, and manage errors effectively.
Key points:
Use GET
for fetching data, POST
for sending data.
Always check readyState
and status
to handle responses properly.
You can send headers and structured data (JSON) for better server communication.
AJAX requests improve user experience by eliminating page reloads.
Mastering AJAX requests is essential for building dynamic, responsive, and modern web applications.
Write an AJAX GET request to fetch data.txt
and display its content inside a <div>
when a button is clicked.
Create an AJAX POST request to send a username and email to submit.php
and display the server response in a <p>
element.
Write code to handle different HTTP status codes (200, 404, 500) and display appropriate messages on the page.
Fetch a JSON file (user.json
) and display the name
and age
of the user in separate <span>
elements.
Modify an AJAX request to show a “Loading…” message while waiting for the server response and replace it with the actual data once received.
Create two buttons that send AJAX requests to two different files (students.txt
and teachers.txt
) and display the content in the same <div>
.
Use setRequestHeader
to send JSON data in a POST request and display the server response.
Write an AJAX request that times out after 5 seconds and shows an alert if the request exceeds this time.
Fetch an HTML snippet (snippet.html
) and insert it into a specific <section>
of the page without reloading the page.
Write a function that sends multiple AJAX requests sequentially and logs each response in the console.
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