Skip to content

Instantly share code, notes, and snippets.

@LiamChapman
Last active February 7, 2018 13:24
Show Gist options
  • Select an option

  • Save LiamChapman/5ce99e27de164f059e5f to your computer and use it in GitHub Desktop.

Select an option

Save LiamChapman/5ce99e27de164f059e5f to your computer and use it in GitHub Desktop.
Quick and Simple XMLHttpRequest
window.xhr = function (url, callback, method, params) {
if (typeof callback !== 'function' ) throw "no callback passed!";
try {
var xmlhttp = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open(method||"GET", url, true);
// uncomment line for laravel xhr requests. otherwise you get 419 error.
//xmlhttp.setRequestHeader('X-CSRF-TOKEN', document.head.querySelector('meta[name="csrf-token"]').getAttribute('content'));
xmlhttp.send(params || '');
} catch (e) {
console.log('xhr', e);
}
}
@LiamChapman
Copy link
Author

basic example:

xhr('/my-url', function (response) {
console.log(response);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment