Skip to content

Instantly share code, notes, and snippets.

@ClementParis016
Created April 1, 2015 20:21
Show Gist options
  • Save ClementParis016/d19ba18b62ad8800710c to your computer and use it in GitHub Desktop.
Save ClementParis016/d19ba18b62ad8800710c to your computer and use it in GitHub Desktop.
AJAX request helper (plain Javascript)
var ajax = {
newRequest: function(method, url, params, callback, context) {
this.context = context;
this.req = new XMLHttpRequest();
this.req.open(method, url, true);
if(params) {
this.params = this.encodeParams(params);
} else {
this.params = '';
}
if(method === 'POST') {
this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
}
var _this = this;
this.req.onload = function() {
if(this.status >= 200 && this.status < 400) {
// AJAX succeed
var data;
if(this.responseText == 0) {
data = { error: 'Invalid action.' };
} else {
data = JSON.parse(this.responseText);
}
callback.call(_this.context, data);
} else {
// Server error
callback.call(_this.context, { error: 'Server error.' });
}
};
this.req.onerror = function() {
// Connection error
callback.call(_this.context, { error: 'Connection error.' });
};
this.sendRequest();
},
encodeParams: function(params) {
// Encode params object to URL params
var encodedParams = Object.keys(params).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
}).join('&');
return encodedParams;
},
sendRequest: function() {
// Send the request
this.req.send(this.params);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment