Skip to content

Instantly share code, notes, and snippets.

@donbrae
Last active July 5, 2022 11:54
Show Gist options
  • Save donbrae/d9ea2f9a012066931e7258e98ec85233 to your computer and use it in GitHub Desktop.
Save donbrae/d9ea2f9a012066931e7258e98ec85233 to your computer and use it in GitHub Desktop.
Vanilla JS Ajax/XHR request
function XHRRequest(url, type = 'text/plain') {
const request = new XMLHttpRequest();
request.open('GET', `${url}?${new Date().getTime()}`, true);
request.setRequestHeader('Content-type', type);
request.onload = function () {
if (this.status >= 200 && this.status < 400) { // Success
console.log('Success', this.response);
} else
console.error('XHR error', this.response);
};
request.onerror = function () {
console.error('XHR connection error');
};
request.send();
}
XHRRequest('https://jsonplaceholder.typicode.com/todos', 'application/json');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment