ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Xmlhttp in Ajax

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='13' AND `tutorial_submenu`='1090' AND `tutorial_status`=1 LIMIT 1

Xmlhttp in Ajax

In the context of AJAX (Asynchronous JavaScript and XML), XMLHttpRequest is the core object that allows you to send HTTP requests and handle responses asynchronously. The XMLHttpRequest object is used to interact with servers, retrieve data, and update parts of a web page without reloading the entire page.

Overview of XMLHttpRequest:

The XMLHttpRequest object allows you to send a request to a web server and receive a response asynchronously, which is what enables dynamic updates to a web page. You can use it to interact with different types of data formats, including XML, JSON, plain text, and more.

Key Features of XMLHttpRequest:

  • Asynchronous Communication: The request to the server is made asynchronously, meaning the page can continue to function while waiting for the server's response.
  • Request Types: You can make different types of HTTP requests (e.g., GET, POST, PUT, DELETE).
  • Handling Responses: You can process the server's response and update the page without reloading it.

Basic Structure of XMLHttpRequest

Here’s a step-by-step breakdown of how to use XMLHttpRequest in AJAX:

  1. Create a New XMLHttpRequest Object: This object is used to send and receive data.
  2. Open a Request: You define the request type (GET, POST, etc.) and the URL for the server endpoint.
  3. Set Up a Callback Function: The callback function handles the response when it is ready.
  4. Send the Request: This sends the request to the server.
  5. Handle the Response: The response can be handled in various formats such as XML, JSON, or plain text.

Example: Using XMLHttpRequest for an AJAX Request

Let’s create an example where we use XMLHttpRequest to fetch data from the server and display it on a webpage. For simplicity, we'll assume the server is returning a JSON response, but the same approach can be used for XML or plain text.

1. Frontend (HTML + JavaScript with XMLHttpRequest)

<!DOCTYPE html>

<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX with XMLHttpRequest</title></head><body> <h1>User Data</h1> <button onclick="loadData()">Load Users</button> <ul id="user-list"></ul> <script> // Function to load data from the server using XMLHttpRequest function loadData() { // Create a new XMLHttpRequest object const xhr = new XMLHttpRequest(); // Open the request: GET method, URL of the server endpoint (for example, "data.json") xhr.open("GET", "data.json", true); // Define the callback function to handle the response xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // When the request is completed and successful (status 200) // Parse the JSON response text const data = JSON.parse(xhr.responseText); // Get the 'user-list' element where the users will be displayed const list = document.getElementById("user-list"); list.innerHTML = ""; // Clear any existing content in the list // Loop through each user and add them to the list data.users.forEach(function(user) { const li = document.createElement('li'); li.textContent = `Name: ${user.name}, Email: ${user.email}`; list.appendChild(li); }); } }; // Send the request xhr.send(); } </script></body></html>

2. Example JSON Response (data.json)

Here’s an example of a JSON file that might be returned by the server:

{

"users": [ { "name": "John Doe", "email": "john.doe@example.com" }, { "name": "Jane Smith", "email": "jane.smith@example.com" } ]}

Explanation of the Example:

  1. Creating XMLHttpRequest Object:

    const xhr = new XMLHttpRequest();

    This creates a new instance of the XMLHttpRequest object, which will be used to send and receive the request.

  2. Opening the Request:

    xhr.open("GET", "data.json", true);

    This specifies that the request method is GET, the URL is data.json, and the request should be asynchronous (true).

  3. Setting the Callback Function:

    xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { // Handle the response }};

    This function will be called every time the readyState of the request changes. The readyState === 4 indicates that the request is complete. The status === 200 indicates that the request was successful.

  4. Parsing the Response:

    const data = JSON.parse(xhr.responseText);

    Once the response is received, the response text is parsed as JSON using JSON.parse().

  5. Updating the DOM:

    data.users.forEach(function(user) { const li = document.createElement('li'); li.textContent = `Name: ${user.name}, Email: ${user.email}`; list.appendChild(li);});

    After parsing the response, the user data is dynamically added to an unordered list (<ul>). Each user's name and email is displayed as a list item (<li>).

  6. Sending the Request:

    xhr.send();

    Finally, the request is sent to the server.


States of XMLHttpRequest

The XMLHttpRequest object has different readyState values, which indicate the progress of the request. Here are the states:

  • 0 (UNSENT): The open() method has not been called yet.
  • 1 (OPENED): The open() method has been called, but the request has not been sent yet.
  • 2 (HEADERS_RECEIVED): The request has been sent, and the response headers are available.
  • 3 (LOADING): The response body is being received (but not completed).
  • 4 (DONE): The request has completed, and the response is available.

You typically check for readyState === 4 to know when the request has finished.


Handling Errors

It’s important to handle errors such as network failures or incorrect URLs. You can add error handling to ensure your application doesn't break.

xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { // Handle the successful response console.log(xhr.responseText); } else { // Handle error (e.g., status code not 200) console.error("Error: " + xhr.statusText); } }};

You can also use the onerror event handler to capture network-related errors:

xhr.onerror = function() { console.error("Network error occurred");};

Example of Sending Data Using POST with XMLHttpRequest

If you need to send data to the server (e.g., to insert a new user), you can use the POST method instead of GET.

Example: Sending Data with POST Method

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX POST Request</title></head><body> <h1>Submit User Data</h1> <form id="user-form"> <input type="text" id="name" placeholder="Enter Name" required> <input type="email" id="email" placeholder="Enter Email" required> <button type="submit">Submit</button> </form> <script> document.getElementById('user-form').addEventListener('submit', function(event) { event.preventDefault(); // Create a new XMLHttpRequest object const xhr = new XMLHttpRequest(); const name = document.getElementById('name').value; const email = document.getElementById('email').value; // Open a POST request to send data to the server xhr.open("POST", "submit_user.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Define the data to send const data = `name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}`; // Handle the response xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log("Data sent successfully: ", xhr.responseText); } }; // Send the request with the data xhr.send(data); }); </script></body></html>

Backend (submit_user.php)

<?php// Get the POST data$name = $_POST['name'];$email = $_POST['email'];// Process the data (e.g., insert into a database)echo "User data received: Name = $name, Email = $email";?>


Conclusion

The XMLHttpRequest object is a powerful tool in AJAX for sending and receiving data asynchronously. It allows you to communicate with the server without reloading the entire page.

  • GET requests can retrieve data from the server.
  • POST requests can send data to the server.
  • Error handling and status checking are essential for robust AJAX interactions.

While newer technologies like fetch() are commonly used today, understanding XMLHttpRequest is still important, especially when working with legacy code or supporting older browsers.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql