Skip to content

Instantly share code, notes, and snippets.

@wpscholar wpscholar/ajax.js
Last active Apr 18, 2019

Embed
What would you like to do?
var url = "";
var params = {
name: 'John',
email: 'webmaster@mysite.com'
};
var xhr = new XMLHttpRequest();
xhr.open('POST', url + '?' + buildQueryString(params));
xhr.responseType = 'json';
xhr.send(null);
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
console.log(xhr.response); // 'This is the returned text.'
} else {
console.log('Error: ' + xhr.status); // An error occurred during the request.
}
}
}
function buildQueryString( params ) {
return Object.keys(params).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
}).join('&');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.