Last active
February 7, 2018 13:24
-
-
Save LiamChapman/5ce99e27de164f059e5f to your computer and use it in GitHub Desktop.
Quick and Simple XMLHttpRequest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
basic example:
xhr('/my-url', function (response) {
console.log(response);
});