-
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 stands for Asynchronous JavaScript and XML, and the core of AJAX communication is the XMLHttpRequest object. This object allows JavaScript to send and receive data from a web server without reloading the page.
Although the name contains “XML,” it can work with any data type—HTML, text, or JSON. The XMLHttpRequest object is one of the oldest yet most reliable ways to make AJAX calls in JavaScript.
The XMLHttpRequest (XHR) object is built into most browsers and lets your JavaScript code communicate directly with the server in the background.
With it, you can:
Send data to the server
Receive data from the server
Update part of a webpage dynamically
This is the base concept behind most modern JavaScript frameworks like React, Angular, and Vue when they perform API requests.
You can create an XHR object using the new
keyword.
// Create an XMLHttpRequest object
let xhr = new XMLHttpRequest();
This object gives you access to several methods and properties that let you send requests and handle responses.
An AJAX request with XMLHttpRequest usually follows these steps:
Create a new XMLHttpRequest object.
Open the request using the open()
method.
Send the request to the server using the send()
method.
Handle the server response using the onreadystatechange
event.
Here’s a simple example that loads data from a file called data.txt
and displays it on the page.
<!DOCTYPE html>
<html>
<body>
<h2>Load Text File using AJAX</h2>
<button onclick="loadData()">Load Content</button>
<div id="output"></div>
<script>
function loadData() {
// Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();
// Define what should happen when the response is ready
xhr.onreadystatechange = function() {
// readyState 4 means the operation is complete
// status 200 means "OK" (successful request)
if (this.readyState == 4 && this.status == 200) {
document.getElementById("output").innerHTML = this.responseText;
}
};
// Initialize a GET request to the file
xhr.open("GET", "data.txt", true);
// Send the request to the server
xhr.send();
}
</script>
</body>
</html>
xhr.open("GET", "data.txt", true)
sets up the request.
"GET"
means we are requesting data.
"data.txt"
is the file we want.
true
makes it asynchronous (the page doesn’t freeze).
xhr.send()
sends the request to the server.
xhr.onreadystatechange
triggers every time the request state changes.
When readyState
is 4
and status
is 200
, the response is available.
The readyState
property shows the current state of the request.
Value | State | Description |
---|---|---|
0 | UNSENT | Request not initialized |
1 | OPENED | Connection established |
2 | HEADERS_RECEIVED | Request received |
3 | LOADING | Processing request |
4 | DONE | Request finished and response ready |
When something goes wrong (like a 404 or network issue), you can handle it properly using the status
code.
if (this.readyState == 4) {
if (this.status == 200) {
console.log("Request successful:", this.responseText);
} else {
console.error("Error loading file:", this.status);
}
}
This ensures your application doesn’t silently fail when the request fails.
While GET
requests fetch data, POST
requests send data to the server.
Example: sending user input to a server file server.php
.
<!DOCTYPE html>
<html>
<body>
<h2>Send Data using POST</h2>
<input type="text" id="username" placeholder="Enter your name">
<button onclick="sendData()">Send</button>
<p id="response"></p>
<script>
function sendData() {
// Get input value
let name = document.getElementById("username").value;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML = this.responseText;
}
};
// Open a POST request
xhr.open("POST", "server.php", true);
// Set request header to send form data
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send data
xhr.send("username=" + encodeURIComponent(name));
}
</script>
</body>
</html>
xhr.open("POST", "server.php", true)
prepares a POST request.
xhr.setRequestHeader()
sets the request type.
xhr.send()
sends the actual data.
The data (username
) is sent to the server-side file for processing.
Most modern applications exchange data in JSON format.
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onload = function() {
if (xhr.status === 200) {
// Parse JSON data
let data = JSON.parse(xhr.responseText);
// Display a value from the JSON
console.log("User Name:", data.name);
}
};
xhr.send();
Here, JSON.parse()
converts the JSON text into a JavaScript object so you can easily use it in your code.
Asynchronous (Recommended):
The code continues running while the request is processed.
This keeps your webpage responsive.
Synchronous:
The page waits for the response, which can cause it to freeze.
Example:
xhr.open("GET", "data.txt", false); // false = synchronous
Synchronous requests are deprecated in modern browsers because they block the user interface.
Method/Property | Description |
---|---|
open(method, url, async) |
Initializes request |
send() |
Sends request to server |
setRequestHeader(header, value) |
Sets HTTP request headers |
readyState |
Holds the current state |
status |
Returns the HTTP status code |
responseText |
Returns response data as text |
onreadystatechange |
Defines a function to call when ready state changes |
The XMLHttpRequest object is the foundation of AJAX communication. It allows data exchange between the client and server without reloading the page. By using its methods like open()
, send()
, and properties like readyState
and status
, you can easily send and receive text, HTML, or JSON data.
Although newer features like Fetch API are now more common, learning XMLHttpRequest is still valuable for understanding how AJAX works at a lower level and for maintaining older codebases.
Create an XMLHttpRequest to fetch a text file (info.txt
) and display its content inside a <div>
when a button is clicked.
Write code to check the readyState
and status
of an XMLHttpRequest and log appropriate messages for loading, success, or failure.
Fetch a JSON file (user.json
) using XMLHttpRequest and display the name
and email
values on the page.
Create a POST request using XMLHttpRequest to send a username and email to submit.php
and display the server response.
Modify an XMLHttpRequest to show a “Loading…” message in a <div>
before the server responds.
Write code that handles errors for XMLHttpRequest requests, logging 404
or 500
errors to the console.
Create two buttons that each send an XMLHttpRequest to different text files (students.txt
and teachers.txt
) and display results in the same <div>
.
Use XMLHttpRequest to fetch an HTML snippet (snippet.html
) and insert it into a specific section of the page without refreshing.
Write code that parses an array of JSON objects from a file and dynamically creates a list of user names and ages in the DOM.
Implement a synchronous XMLHttpRequest (for learning only) and observe how it blocks page interaction until the response is received.
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