Some Examples…
Making an AJAX request using XMLHttpRequest
// Making an AJAX request using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Making a POST request using XMLHttpRequest
// Making a POST request using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/submit-data', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('Response:', xhr.responseText);
}
};
xhr.send(JSON.stringify({ key: 'value' }));
Making an AJAX request using Fetch API with async/await
// Making an AJAX request using Fetch API with async/await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchData();
Tracking progress with XMLHttpRequest
// Tracking progress with XMLHttpRequest
const xhrProgress = new XMLHttpRequest();
xhrProgress.open('GET', 'https://api.example.com/large-data', true);
xhrProgress.onprogress = function(event) {
if (event.lengthComputable) {
const percentComplete = event.loaded / event.total * 100;
console.log(`Progress: ${percentComplete.toFixed(2)}%`);
} else {
console.log('Unable to compute progress information since the total size is unknown');
}
};
xhrProgress.onload = function() {
if (xhrProgress.status === 200) {
console.log('Download complete:', xhrProgress.responseText);
}
};
xhrProgress.send();
Fetch API request with a timeout
// Fetch API request with a timeout
const fetchWithTimeout = (resource, options) => {
const { timeout = 8000 } = options;
const fetchPromise = fetch(resource, options);
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Request timed out')), timeout);
});
return Promise.race([fetchPromise, timeoutPromise]);
};
fetchWithTimeout('https://api.example.com/data', {})
.then(response => response.json())
.then(data => console.log('Data:', data))
.catch(error => console.error('Error:', error));
Fetch API request with a timeout
// Fetch API request with a timeout
const fetchWithTimeout = (resource, options) => {
const { timeout = 8000 } = options;
const fetchPromise = fetch(resource, options);
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Request timed out')), timeout);
});
return Promise.race([fetchPromise, timeoutPromise]);
};
fetchWithTimeout('https://api.example.com/data', {})
.then(response => response.json())
.then(data => console.log('Data:', data))
.catch(error => console.error('Error:', error));
Setting responseType in XMLHttpRequest
// Setting responseType in XMLHttpRequest
const xhrResponseType = new XMLHttpRequest();
xhrResponseType.open('GET', 'https://api.example.com/data', true);
xhrResponseType.responseType = 'json'; // Expecting JSON response
xhrResponseType.onload = function() {
if (xhrResponseType.status === 200) {
console.log('JSON Response:', xhrResponseType.response);
}
};
xhrResponseType.send();
Canceling a Fetch request
// Canceling a Fetch request
const controller = new AbortController();
const signal = controller.signal;
fetch('https://api.example.com/data', { signal })
.then(response => response.json())
.then(data => console.log('Data:', data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Fetch error:', error);
}
});
// Cancel the request
controller.abort();
Fetching binary data with XMLHttpRequest
// Fetching binary data with XMLHttpRequest
const xhrBinary = new XMLHttpRequest();
xhrBinary.open('GET', 'https://api.example.com/image', true);
xhrBinary.responseType = 'blob'; // Set response type to blob for binary data
xhrBinary.onload = function() {
if (xhrBinary.status === 200) {
const blob = xhrBinary.response;
const img = document.createElement('img');
img.src = URL.createObjectURL(blob);
document.body.appendChild(img);
}
};
xhrBinary.send();