Skip to content

Instantly share code, notes, and snippets.

@tcha-tcho
Created June 26, 2023 14:51
Show Gist options
  • Save tcha-tcho/6bc36e49d726fa17b929cd87991fbce1 to your computer and use it in GitHub Desktop.
Save tcha-tcho/6bc36e49d726fa17b929cd87991fbce1 to your computer and use it in GitHub Desktop.
Quick method to Ajax with pure JS
let fetch = (url, body) => {
return new Promise( async function (resolve, reject) {
// IF MODERN BROWSER > CREATE NEW httpRequest
let httpRequest;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
}
// IF IE > CREATE NEW ActiveXObject
else if (window.ActiveXObject) {
try {
httpRequest = new window.ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpRequest = new window.ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
// UNABLE TO CREATE httpRequest
if (!httpRequest) {
resolve( false );
}
//add a listener for the "load" event, which
//will happen when the data returns
httpRequest.addEventListener("load", function() {
if (httpRequest.status >= 200 && httpRequest.status < 400) {
const txt = httpRequest.responseText; // Success!
resolve( txt[0] === "{" || txt[0] === "[" ? JSON.parse(txt) : txt );
} else {
// We reached our target server, but it returned an error
reject(httpRequest.status)
}
});
//add a listener for the "error" event, which
//will happen if there was a network error
httpRequest.addEventListener("error", function(e) {
reject(e)
})
// SEND REQUEST
httpRequest.open(body?'POST':'GET', url);
httpRequest.send(body?JSON.stringify(body):undefined);
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment