Home » 
        XML Tutorial
    
    XML - XMLHttpRequest
    
        
            By IncludeHelp Last updated : December 29, 2024
        
    
    The XMLHttpRequest object is a built-in feature of modern browsers that allows web developers to interact with servers without refreshing the webpage. It supports making HTTP requests and receiving responses dynamically, enabling the creation of interactive and seamless web applications. Despite its name, XMLHttpRequest works with various formats such as JSON, XML, text, and even binary data.
How to Use XMLHttpRequest?
To use XMLHttpRequest, follow these steps:
1. Creating an XMLHttpRequest Object
let xhr = new XMLHttpRequest();
2. Configuring the Request
Use the open() method to set up the request.
xhr.open('GET', 'https://api.example.com/data', true);
Parameters
- Method: HTTP method (e.g., 
GET, POST). 
- URL: The endpoint to fetch or send data.
 
- Async: Boolean indicating whether the operation is asynchronous (default is 
true). 
3. Sending the Request
xhr.send();
For POST requests, include the request body:
xhr.send(JSON.stringify({ key: 'value' }));
4. Handling the Response
Attach event handlers to process the response.
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(`Response: ${xhr.responseText}`);
  } else {
    console.error(`Error ${xhr.status}: ${xhr.statusText}`);
  }
};
xhr.onerror = function() {
  console.error('Request failed');
};
Example 1: Fetching Text Data
This example fetches plain text from the server and displays it on the webpage.
HTML
<div id="demo">Loading...</div>
JavaScript
let xhr = new XMLHttpRequest();
xhr.onload = function() {
  if (xhr.status === 200) {
    document.getElementById("demo").innerText = xhr.responseText;
  } else {
    console.error(`Error ${xhr.status}: ${xhr.statusText}`);
  }
};
xhr.open('GET', '/example.txt', true);
xhr.send();
Explanation
- Create an XMLHttpRequest Object: let 
xhr = new XMLHttpRequest(); 
- Define the onload Handler: The function executes after the request completes. It updates the 
div with the server response if the status is 200 (OK). 
- Configure and Send the Request: 
xhr.open() sets the request method and URL, and xhr.send() initiates it. 
Example 2: Sending Data to the Server
Send user data to the server using a POST request.
JavaScript
let xhr = new XMLHttpRequest();
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log('Data sent successfully!');
  } else {
    console.error(`Error ${xhr.status}: ${xhr.statusText}`);
  }
};
xhr.open('POST', '/submit', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ name: 'John Doe', age: 30 }));
Explanation
- Set Up the Request: Use 
xhr.open('POST', '/submit', true) for a POST request. 
- Set Headers: Use 
xhr.setRequestHeader to specify the content type as JSON. 
- Send Data: Convert the object to JSON with 
JSON.stringify() and pass it to xhr.send(). 
- Handle the Response: Use the 
onload handler to log success or errors. 
Example 3: Handling Progress Events
Track the download progress of a file.
JavaScript
let xhr = new XMLHttpRequest();
xhr.onprogress = function(event) {
  if (event.lengthComputable) {
    console.log(`Downloaded ${event.loaded} of ${event.total} bytes`);
  } else {
    console.log(`Downloaded ${event.loaded} bytes`);
  }
};
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log('Download complete!');
  }
};
xhr.open('GET', '/large-file.zip', true);
xhr.send();
Explanation
- Monitor Progress: Use the 
onprogress event to track how much data has been downloaded. 
- Check lengthComputable: Log progress as percentages if total size is known.
 
- Handle Completion: Use onload to confirm when the download finishes.
 
	
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement