-
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
In AJAX, the response is the data returned by the server after a request. Handling the response correctly is key to making web pages dynamic and interactive.
AJAX allows JavaScript to receive this data without reloading the page, which creates smoother user experiences. Responses can be text, HTML, JSON, or XML, depending on the server and application needs.
An AJAX response is the data sent from the server back to the client after a request is made.
When using XMLHttpRequest, the response is accessed through:
responseText
– Returns the response as plain text.
responseXML
– Returns the response as an XML document.
status
– Returns the HTTP status code (e.g., 200 for success).
Here’s the general way to handle responses using XMLHttpRequest:
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // Request is complete
if (xhr.status === 200) { // Successful response
console.log("Server Response:", xhr.responseText);
} else {
console.error("Error:", xhr.status);
}
}
};
xhr.send();
Explanation:
readyState === 4
ensures the request is complete.
status === 200
confirms a successful server response.
xhr.responseText
contains the data sent by the server.
Modern web applications often use JSON for responses because it is easy to read and parse.
user.json
{
"name": "Vicky",
"age": 28,
"email": "vicky@example.com"
}
JavaScript to handle it:
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 string to JS object
document.getElementById("output").innerHTML =
`Name: ${user.name}<br>Age: ${user.age}<br>Email: ${user.email}`;
}
};
xhr.send();
Explanation:
JSON.parse()
converts JSON into a usable JavaScript object.
Data is displayed dynamically in a <div>
with id "output"
.
AJAX responses can also be HTML snippets that can be inserted directly into a page.
let xhr = new XMLHttpRequest();
xhr.open("GET", "snippet.html", true);
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById("container").innerHTML = xhr.responseText;
}
};
xhr.send();
Explanation:
xhr.responseText
contains the HTML snippet.
innerHTML
inserts the content without refreshing the page.
This method is commonly used for dynamic content loading, like tabs or partial page updates.
If the server sends XML data, it can be accessed using responseXML
.
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onload = function() {
if (xhr.status === 200) {
let xml = xhr.responseXML;
let items = xml.getElementsByTagName("item");
for (let i = 0; i < items.length; i++) {
console.log(items[i].textContent);
}
}
};
xhr.send();
Explanation:
xhr.responseXML
returns a parsed XML document.
You can traverse XML nodes using standard DOM methods like getElementsByTagName()
.
Always check the status
code to ensure the response is valid. Common HTTP status codes include:
Status | Meaning |
---|---|
200 | OK – successful request |
404 | Not Found – file or endpoint missing |
500 | Server Error – internal server issue |
403 | Forbidden – no permission |
Example:
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("Success:", xhr.responseText);
} else if (xhr.status === 404) {
alert("File not found.");
} else {
alert("Server error: " + xhr.status);
}
}
};
onload
Eventonload
is an alternative to onreadystatechange
for simpler AJAX requests. It runs when the request completes successfully.
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById("output").textContent = xhr.responseText;
} else {
console.error("Error:", xhr.status);
}
};
xhr.send();
Advantages:
Easier to use than onreadystatechange
.
Only triggers when the request finishes, so no need to check readyState
.
AJAX responses can be used to update sections of a webpage dynamically.
<button id="loadBtn">Load Response</button>
<div id="output"></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("output").innerHTML = xhr.responseText;
} else {
document.getElementById("output").textContent = "Failed to load data";
}
};
xhr.send();
});
</script>
Explanation:
Clicking the button sends the request.
The response updates only the <div>
.
No page reload is required.
An AJAX response is the data sent back from the server after a request. Properly handling it allows developers to create dynamic and interactive web applications.
Key points:
Responses can be text, HTML, JSON, or XML.
Always check the HTTP status code to confirm success.
Use onload
or onreadystatechange
to handle responses.
Parse JSON responses using JSON.parse()
.
Insert HTML responses into the DOM to update parts of the page.
Understanding AJAX responses is essential for building modern web apps, real-time dashboards, and dynamic content updates.
Write an AJAX request to fetch data.txt
and display its content inside a <div>
when a button is clicked.
Fetch a JSON file (user.json
) and display the name
and email
values in separate <p>
elements.
Write code to handle HTML responses by fetching snippet.html
and inserting it into a <section>
without reloading the page.
Fetch an XML file (data.xml
) and log all <item>
values in the console.
Create an AJAX request that shows a “Loading…” message while waiting for the server response and replaces it with the actual data once received.
Write code to handle different HTTP status codes (200, 404, 500) and display appropriate messages in a <div>
.
Use onload
to handle a server response from info.txt
and display it in a <p>
element.
Parse a JSON array from users.json
and create a dynamic list of user names in the DOM.
Create a button that fetches an HTML snippet and appends it to an existing <div>
every time the button is clicked.
Write an AJAX request that fetches data from data.txt
and logs an error message in the console if the request fails.
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