Here’s a cheat sheet for AJAX (Asynchronous JavaScript and XML):
XMLHttpRequest Object
// Create XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure the request (GET request to a URL)
xhr.open("GET", "https://example.com/data", true);
// Set callback function for handling the response
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Process the response
console.log(xhr.responseText);
}
};
// Send the request
xhr.send();
Fetch API
// Fetch data using Fetch API
fetch("https://example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
jQuery AJAX
// Using jQuery for AJAX
$.ajax({
url: "https://example.com/data",
method: "GET",
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(error) {
console.error("Error:", error);
}
});
Sending Data (POST Request)
// Sending data with XMLHttpRequest (POST request)
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://example.com/postData", true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = {
key1: "value1",
key2: "value2"
};
xhr.send(JSON.stringify(data));
Handling Cross-Origin Requests (CORS)
// Handling CORS with XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.withCredentials = true; // Include credentials (cookies) in the request
// ... (rest of the XMLHttpRequest code)
AJAX Events
// AJAX Events with XMLHttpRequest
xhr.addEventListener("load", function() {
console.log("Request completed successfully");
});
xhr.addEventListener("error", function() {
console.error("Error occurred during the request");
});
xhr.addEventListener("abort", function() {
console.warn("Request aborted");
});
Aborting a Request
// Abort an XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/data", true);
xhr.send();
// Abort the request
xhr.abort();
Handling JSONP (JSON with Padding)
// JSONP request using a script tag
function handleJSONP(response) {
console.log(response);
}
var script = document.createElement("script");
script.src = "https://api.example.com/data?callback=handleJSONP";
document.body.appendChild(script);
This cheat sheet covers some fundamental concepts and examples of AJAX using vanilla JavaScript, Fetch API, and jQuery. Keep in mind that modern web development often utilizes Fetch API and other libraries/frameworks for asynchronous requests. Adjust the examples based on your project’s needs.