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:
new XMLHttpRequest()
.open()
method with the HTTP method (GET, POST, etc.) and the URL of the server.xhr.onload
) to handle the response when the request completes.<div>
element with the response text (xhr.responseText
).send()
method.This is a basic example of how XMLHttpRequest works to fetch data from a server asynchronously and update the web page dynamically.
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:
new XMLHttpRequest()
.open()
method with the HTTP method (GET, POST, etc.) and the URL of the server.xhr.onload
) to handle the response when the request completes successfully. Inside this callback function, we check the status of the response and log the response data to the console if the request is successful.xhr.onerror
) to handle errors if the request fails.send()
method.