Related Topics
Introduction
Html page 1
Html page 2
Html page3
Html page4
HTML Elements and structure
Html page 5
Html page 6
Html page 7
HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10
HTML Lists and Tables
Html page 11
Html page 12
Html page 13
HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16
HTML Images and Media
Html page 17
Html page 18
HTML Links and Anchors
Html page 19
Html page 20
Html page 21
HTML Styles and Formatting
Html page 22
HTML Semantic Elements
Html page 23
Html page 24
HTML Attributes
Html page 25
Html page 26
HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30
HTML Document and Browser Support
Html page 31
Html page 32
HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36
HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39
HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42
Introduction
Data Structure Page 1
Data Structure Page 2
Data Structure Page 3
Data Structure Page 4
Data Structure Page 5
Data Structure Page 6
Data Structure Page 7
Data Structure Page 8
String
Data Structure Page 9
Data Structure Page 10
Data Structure Page 11
Data Structure Page 12
Data Structure Page 13
Array
Data Structure Page 14
Data Structure Page 15
Data Structure Page 16
Data Structure Page 17
Data Structure Page 18
Linked List
Data Structure Page 19
Data Structure Page 20
Stack
Data Structure Page 21
Data Structure Page 22
Queue
Data Structure Page 23
Data Structure Page 24
Tree
Data Structure Page 25
Data Structure Page 26
Binary Tree
Data Structure Page 27
Data Structure Page 28
Heap
Data Structure Page 29
Data Structure Page 30
Graph
Data Structure Page 31
Data Structure Page 32
Searching Sorting
Data Structure Page 33
Hashing Collision
Data Structure Page 35
Data Structure Page 36

JAVASCRIPT
// Creating an XMLHttpRequest object
const xhr = new XMLHttpRequest();
// Configuring the request (GET request to a JSON API)
xhr.open('GET', 'https://api.example.com/data', true);
// Handling the response
xhr.onload = function() {
if (xhr.status === 200) {
// Parse the JSON response
const data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.error('Request failed:', xhr.status);
}
};
// Handling errors
xhr.onerror = function() {
console.error('Request failed.');
};
// Sending the request
xhr.send();
The response data can then be used to update the web page content dynamically, without requiring a full page refresh. AJAX has become a fundamental part of modern web development, enabling more interactive and responsive web applications.
const xhr = new XMLHttpRequest();
2. Configure the Request: Next, you need to configure the AJAX request by specifying the HTTP method, URL, and other options. You can use methods like open()
to set up the request details.
xhr.open('GET', 'https://api.example.com/data', true);
In this example, we are making a GET request to the URL ‘https://api.example.com/data‘ asynchronously (the true
parameter indicates asynchronous mode).
Handle the Response: To handle the response from the server, you set up an event listener, typically the
onload
event, which fires when the server responds to the request.
xhr.onload = function() {
if (xhr.status === 200) {
// Handle the successful response
const data = xhr.responseText; // Response data in plain text format
// Process and use the response data here
} else {
// Handle error responses
console.error('Request failed:', xhr.status);
}
};
In the event handler, you can check the HTTP status code (xhr.status
) to determine if the request was successful (status code 200) or if there was an error (e.g., 404 for “not found” or 500 for “server error”).
Handle Errors: Additionally, you can set up an
onerror
event handler to handle network errors that may occur during the request.
xhr.onerror = function() {
console.error('Request failed.');
};
Send the Request: Once the configuration is complete and event handlers are set, you can send the actual AJAX request using the
send()
method.
xhr.send();
Use the Response Data: When the server responds, the
onload
event is triggered, and the response data is available in thexhr.responseText
property. You can then process and use this data in your JavaScript code as needed.
It’s essential to note that the XMLHttpRequest object is considered an older approach to making AJAX requests. Modern web development often utilizes more convenient and powerful methods, such as the Fetch API and third-party libraries like Axios and Fetch API, which provide more user-friendly APIs for AJAX requests and better support for promises and async/await patterns. However, the basic concepts of making AJAX requests remain the same across these different methods.
const xhr = new XMLHttpRequest();
xhr.onerror = function() {
console.error('Request failed.');
};
// Continue setting up the request and other event handlers here
Handle HTTP Status Codes: The server may respond with different HTTP status codes to indicate the success or failure of the request. You can check the status code in the
onload
event handler to determine the outcome of the request.
xhr.onload = function() {
if (xhr.status === 200) {
// Request was successful, process the response data
} else {
// Handle error based on the status code
console.error('Request failed with status:', xhr.status);
// You can also check other status codes, like 404 (Not Found) or 500 (Internal Server Error)
}
};
3. Parse the Response: In some cases, the server might return an error message or relevant data along with the error status code. Parse the response data to extract any error messages or relevant information for error handling.
xhr.onload = function() {
if (xhr.status === 200) {
// Request was successful, process the response data
} else {
const errorResponse = JSON.parse(xhr.responseText);
console.error('Request failed:', errorResponse.message);
}
};
Handle Server-Side Errors: If the server-side logic encounters an error, it should return an appropriate error response with an error message or code. In the
onload
event handler, you can extract and display the error message to the user.Graceful User Feedback: When an error occurs, provide clear and user-friendly feedback to help users understand what went wrong. Display an error message or notification on the page, guiding users on what steps they should take next.
xhr.onerror = function() {
console.error('Request failed. Please check your internet connection and try again.');
};
xhr.onload = function() {
if (xhr.status === 200) {
// Request was successful, process the response data
} else {
const errorResponse = JSON.parse(xhr.responseText);
console.error('Request failed:', errorResponse.message);
// Display an error message to the user on the page
showErrorToUser(errorResponse.message);
}
};
Remember that error handling should be done both on the client-side and the server-side. Ensure that your server responds with appropriate status codes and error messages to aid in client-side error handling. Good error handling enhances the user experience and helps developers identify and address issues effectively.
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', false); // Synchronous flag set to true
xhr.send();
// Code execution waits for the response before continuing
console.log(xhr.responseText);
Asynchronous Requests:
Flow of Execution: Asynchronous requests, on the other hand, do not block the execution of the program. They allow the code to continue executing other tasks while the request is being made, without waiting for the response. The response is handled separately when it becomes available.
User Experience: Asynchronous requests significantly improve the user experience since they do not freeze the UI. The web page remains responsive, and users can continue interacting with the page while the request is in progress. Once the response is received, the corresponding callback or event handler processes the data.
Example (JavaScript with Fetch API):
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Asynchronous requests are the preferred approach in modern web development because they prevent the UI from becoming unresponsive, resulting in a smoother and more interactive user experience. Technologies like AJAX, Fetch API, and asynchronous functions (e.g., async/await) have made it easier for developers to work with asynchronous requests and handle responses efficiently.
In summary, synchronous requests block program execution until the response is received, while asynchronous requests allow code to continue executing and handle responses separately when they become available. Asynchronous requests are preferred for better user experiences, especially in web applications that require responsiveness and interactivity.




Popular Category
Topics for You
Introduction
Html page 1
Html page 2
Html page3
Html page4
HTML Elements and structure
Html page 5
Html page 6
Html page 7
HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10
HTML Lists and Tables
Html page 11
Html page 12
Html page 13
HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16
HTML Images and Media
Html page 17
Html page 18
HTML Links and Anchors
Html page 19
Html page 20
Html page 21
HTML Styles and Formatting
Html page 22
HTML Semantic Elements
Html page 23
Html page 24
HTML Attributes
Html page 25
Html page 26
HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30
HTML Document and Browser Support
Html page 31
Html page 32
HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36
HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39
HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42
Introduction
Data Structure Page 1
Data Structure Page 2
Data Structure Page 3
Data Structure Page 4
Data Structure Page 5
Data Structure Page 6
Data Structure Page 7
Data Structure Page 8
String
Data Structure Page 9
Data Structure Page 10
Data Structure Page 11
Data Structure Page 12
Data Structure Page 13
Array
Data Structure Page 14
Data Structure Page 15
Data Structure Page 16
Data Structure Page 17
Data Structure Page 18
Linked List
Data Structure Page 19
Data Structure Page 20
Stack
Data Structure Page 21
Data Structure Page 22
Queue
Data Structure Page 23
Data Structure Page 24
Tree
Data Structure Page 25
Data Structure Page 26
Binary Tree
Data Structure Page 27
Data Structure Page 28
Heap
Data Structure Page 29
Data Structure Page 30
Graph
Data Structure Page 31
Data Structure Page 32
Searching Sorting
Data Structure Page 33
Hashing Collision
Data Structure Page 35
Data Structure Page 36
Go through our study material. Your Job is awaiting.