How can I make an AJAX call without jQuery?
If you are a JavaScript developer, you are probably familiar with jQuery’s AJAX functionality. However, there may be instances where you want to make an AJAX call without relying on the jQuery library. In this article, we will explore two different approaches to achieve this.
1. Using the XMLHttpRequest Object
The XMLHttpRequest object is a built-in JavaScript object that allows you to make HTTP requests. Here’s an example of how you can use it to make an AJAX call:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
// Process the response here
}
};
xhr.send();
2. Using the Fetch API
The Fetch API is a newer JavaScript API that provides a more modern and flexible way to make AJAX requests. Here’s an example of how you can use it:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Process the data here
})
.catch(error => {
// Handle any errors here
});
Both approaches allow you to make AJAX calls without relying on jQuery. The XMLHttpRequest approach is more widely supported, but the Fetch API provides a more modern and convenient syntax.
It’s important to note that both approaches require the server to support Cross-Origin Resource Sharing (CORS) if you are making AJAX calls to a different domain.
Now that you have learned how to make AJAX calls without jQuery, you can choose the approach that best fits your needs and start building powerful web applications!
Leave a Reply