Created
January 16, 2018 11:59
-
-
Save promatik/50311c5f5a974f7ecf559e4cd09eb9a7 to your computer and use it in GitHub Desktop.
Javascript AJAX call
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
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