AJAX

Asynchronous JavaScript and XML: Making Dynamic Web Applications

AJAX in JavaScript

AJAX stands for Asynchronous JavaScript and XML. It allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it's possible to update parts of a web page without reloading the whole page.

XMLHttpRequest Object

The XMLHttpRequest object is the foundation of AJAX. Here's how to create and use it:

const xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};

xhr.open("GET", "https://api.example.com/data", true);
xhr.send();

Fetch API

The Fetch API provides a more powerful and flexible feature set for making HTTP requests. Here's an example:

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});

Async/Await with Fetch

Using async/await with Fetch can make your code even cleaner:

async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}

fetchData();

AJAX with jQuery

If you're using jQuery, it provides a simplified way to make AJAX requests:

$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});