Create a JavaScript AJAX GET request
Create a simple function that sends an AJAX GET request and returns a JSON response.
Code
Send a GET request through AJAX with a JSON response.
- ES5 version using XMLHttpRequest
- ES6 version using XMLHttpRequest
- ES6 version using fetch()
JavaScript ES5 using XMLHttpRequest
Sometimes you need a legacy version for compatibility with legacy code; use the ES5 version.
function sendGetRequest(url) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
} else {
console.error(xhr.statusText);
}
};
xhr.onerror = function() {
console.error(xhr.statusText);
};
xhr.open('GET', url);
xhr.send();
}
JavaScript ES6 using XMLHttpRequest
The only difference is const
vs var
.
function sendGetRequest(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
} else {
console.error(xhr.statusText);
}
};
xhr.onerror = function() {
console.error(xhr.statusText);
};
xhr.open('GET', url);
xhr.send();
}
JavaScript ES6 using fetch()
function sendGetRequest(url) {
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
}