Skip to content

Instantly share code, notes, and snippets.

@promatik
Created January 16, 2018 11:59
Show Gist options
  • Save promatik/50311c5f5a974f7ecf559e4cd09eb9a7 to your computer and use it in GitHub Desktop.
Save promatik/50311c5f5a974f7ecf559e4cd09eb9a7 to your computer and use it in GitHub Desktop.
Javascript AJAX call
ajax = (url, data, success, error, method) => {
var params = typeof data == 'string' ? data : Object.keys(data).map(
k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k])
).join('&');
if(method === undefined)
method = "POST";
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onreadystatechange = e => {
if (xhr.readyState > 3) {
if(xhr.status == 200) {
if(success != undefined) {
try {
success(JSON.parse(xhr.responseText));
} catch(e) {
success(xhr.responseText);
}
}
} else {
error != undefined ? error() : 0;
}
}
};
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
return xhr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment