Thursday, January 23, 2025
HomeTechHow to make ajax call from JavaScript

How to make ajax call from JavaScript

To make an AJAX (Asynchronous JavaScript and XML) call from JavaScript, you can use the XMLHttpRequest object or the more modern fetch API. Here’s how you can do both:

1. Using XMLHttpRequest (older method):

// Create a new instance of XMLHttpRequest
var xhr = new XMLHttpRequest();

// Configure the request (GET or POST, URL, asynchronous)
xhr.open('GET', 'https://api.example.com/data', true);

// Set up a function to handle the response when it's ready
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    // Parse the response JSON (if it's JSON data)
    var response = JSON.parse(xhr.responseText);
    console.log(response);
  }
};

// Send the request
xhr.send();

2. Using the fetch API (modern approach):

// Use the fetch API to make a GET request
fetch('https://api.example.com/data')
  .then(response => {
    // Check if the request was successful
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // Parse the JSON data
  })
  .then(data => {
    console.log(data); // Handle the parsed data
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Key differences:

  • XMLHttpRequest: An older method that’s more complex and callback-based.
  • fetch: More modern, returns Promises, and is generally simpler to work with for handling asynchronous requests.
See also  Difference Between Google and Google Chrome

Let me know if you need a specific example or further explanation!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x