Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing XML

XML HttpRequest:



An XMLHttpRequest (XHR) is a JavaScript object used to interact with servers asynchronously. It allows web pages to send and receive data from a server without having to reload the entire page. This enables dynamic updates and interactive user experiences on web applications.

Here's a simple explanation with an example:

Suppose you have a web page that needs to fetch some data from a server and display it to the user. You can use XMLHttpRequest to accomplish this task.

        

Example

<!DOCTYPE html> <html> <head> <title>XMLHttpRequest Example</title> </head> <body> <div id="data"></div> <script> // Create a new XMLHttpRequest object var xhr = new XMLHttpRequest(); // Configure the request (GET request to a URL) xhr.open('GET', 'https://api.example.com/data', true); // Define a callback function to handle the response xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { // If the request is successful, update the HTML content document.getElementById('data').innerHTML = xhr.responseText; } else { // If the request fails, display an error message console.error('Request failed: ' + xhr.statusText); } }; // Send the request xhr.send(); </script> </body> </html>

In this example:

This is a basic example of how XMLHttpRequest works to fetch data from a server asynchronously and update the web page dynamically.


XMLHttpRequest Example

Here's a simple example of how you can use XMLHttpRequest in JavaScript to fetch data from a server:

        

Example

// Create a new XMLHttpRequest object var xhr = new XMLHttpRequest(); // Configure the request (GET request to a URL) xhr.open('GET', 'https://api.example.com/data', true); // Define a callback function to handle the response xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { // If the request is successful, log the response data console.log(xhr.responseText); } else { // If the request fails, log an error message console.error('Request failed: ' + xhr.statusText); } }; // Define a callback function to handle errors xhr.onerror = function() { console.error('Request failed'); }; // Send the request xhr.send();

In this example:





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java