Skip to content

Instantly share code, notes, and snippets.

@garsaud
Last active October 9, 2024 15:29
Show Gist options
  • Save garsaud/1526379593ac5b0947f49b40ca3f87d7 to your computer and use it in GitHub Desktop.
Save garsaud/1526379593ac5b0947f49b40ca3f87d7 to your computer and use it in GitHub Desktop.
Vanilla JS ajax
// Using with(){} — Deprecated but practical
with (new XMLHttpRequest()) {
open('get', 'search?q='+encodeURIComponent('chaises'), true);
onreadystatechange = function () {
if (readyState !== 4 || status !== 200) return;
console.log(JSON.parse(responseText));
};
send();
}
// The classic way
var xhr = new XMLHttpRequest();
xhr.open('get', 'search?q='+encodeURIComponent('chaises'), true);
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4 || xhr.status !== 200) return;
console.log(JSON.parse(xhr.responseText));
};
xhr.send();
// Post request + es6 + synchronous
const xhr = new XMLHttpRequest();
xhr.open('post', url, false);
xhr.onreadystatechange = () => xhr.status === 200 && document.location.reload();
xhr.send(formData);
// Proxying XHR
var originalXhrOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
console.log(arguments);
this.addEventListener("readystatechange", function () {
console.log(this);
}, false);
return originalXhrOpen.apply(this, [].slice.call(arguments));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment