
Request in Ajax
In AJAX, making a request typically involves using JavaScript to send an HTTP request to a server and receiving a response, all without reloading the page. This can be done using various methods, including XMLHttpRequest
(the traditional method) or the newer fetch()
API.
Here’s a detailed explanation of both methods to send requests in AJAX:
1. AJAX Request with XMLHttpRequest
The XMLHttpRequest
object is the traditional way of sending AJAX requests. It allows you to send HTTP requests to the server and receive responses asynchronously.
Example of Making a GET Request with XMLHttpRequest
:
<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>AJAX GET Request Example</h1> <button onclick="loadData()">Get Data</button> <div id="response"></div> <script> function loadData() { const xhr = new XMLHttpRequest(); // Create a new XMLHttpRequest object xhr.open("GET", "data.txt", true); // Initialize the request (GET method, data.txt file) // Set up the callback function to handle the response xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // When request is complete and successful document.getElementById("response").innerText = xhr.responseText; // Display the response } }; xhr.send(); // Send the request to the server } </script></body></html>
Explanation:
- When the user clicks the "Get Data" button, the
loadData
function is called. - This creates a new
XMLHttpRequest
object, opens a GET request to fetch data fromdata.txt
, and sends it to the server. - The server's response is handled in the
onreadystatechange
callback function. If the request is complete (readyState 4) and successful (status 200), the response is displayed in thediv
with the IDresponse
.
2. AJAX Request with the fetch()
API
The fetch()
API is a modern and more convenient alternative to XMLHttpRequest
. It simplifies sending requests and handling responses.
Example of Making a GET Request with fetch()
:
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX with Fetch API</title></head><body> <h1>AJAX GET Request Example</h1> <button onclick="loadData()">Get Data</button> <div id="response"></div> <script> function loadData() { fetch('data.txt') // Initiate the GET request to data.txt .then(response => { if (!response.ok) { // Check if the response is successful throw new Error('Network response was not ok'); } return response.text(); // Parse the response body as text }) .then(data => { document.getElementById('response').innerText = data; // Display the data }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }); } </script></body></html>
Explanation:
- The
fetch()
function is used to send a GET request todata.txt
. - The
.then()
method handles the response once it is received. If the response is successful, the data is converted into text and displayed in theresponse
div. - If there’s any issue with the request or response, the error is caught and logged in the console.
3. AJAX POST Request Example
To send data to the server, a POST request is used. Here's an example of sending data via a POST request with both XMLHttpRequest
and fetch()
.
Example of Sending a POST Request with XMLHttpRequest
:
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX POST Request Example</title></head><body> <h1>AJAX POST Request</h1> <form id="myForm"> <label for="name">Name: </label> <input type="text" id="name" name="name" required> <input type="submit" value="Submit"> </form> <div id="response"></div> <script> document.getElementById('myForm').addEventListener('submit', function(event) { event.preventDefault(); // Prevent the form from submitting normally const name = document.getElementById('name').value; // Get form data const xhr = new XMLHttpRequest(); xhr.open('POST', 'submit_form.php', true); // Send POST request to submit_form.php // Set Content-Type header for form submission xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Set up the callback function to handle the response xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById('response').innerText = xhr.responseText; // Display response } }; // Send the form data (name) xhr.send('name=' + encodeURIComponent(name)); }); </script></body></html>
Explanation:
- The form sends a POST request to
submit_form.php
with the user's name. - The form data is sent as URL-encoded data (
name=value
format). - The response from the server is displayed inside the
response
div.
Example of Sending a POST Request with fetch()
:
<html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX POST Request Example</title></head><body> <h1>AJAX POST Request</h1> <form id="myForm"> <label for="name">Name: </label> <input type="text" id="name" name="name" required> <input type="submit" value="Submit"> </form> <div id="response"></div> <script> document.getElementById('myForm').addEventListener('submit', function(event) { event.preventDefault(); // Prevent the form from submitting normally const name = document.getElementById('name').value; // Get form data fetch('submit_form.php', { method: 'POST', // POST request headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `name=${encodeURIComponent(name)}` // Send form data as URL-encoded string }) .then(response => response.text()) // Parse the response as text .then(data => { document.getElementById('response').innerText = data; // Display response }) .catch(error => { console.error('Error:', error); }); }); </script></body></html>
Explanation:
- The form submits data to
submit_form.php
using thefetch()
method. - Data is sent as URL-encoded using the
body
property. - The server's response is displayed in the
response
div.
Conclusion
XMLHttpRequest
is the older, traditional way to make AJAX requests, allowing both GET and POST methods.fetch()
is the modern, cleaner API to handle requests and responses asynchronously, providing promises for easier handling of responses.
Both methods allow you to make requests to the server asynchronously, enabling dynamic, fast interactions without requiring full page reloads. Using fetch()
is generally recommended for new projects due to its simplicity and ease of use.