Skip to content

Instantly share code, notes, and snippets.

@bendem
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bendem/c5a038e0045470a5e50f to your computer and use it in GitHub Desktop.
Save bendem/c5a038e0045470a5e50f to your computer and use it in GitHub Desktop.
// Simple ajax thing to send stuff
// @param url string
// @param success callback
// @param method string (optional)
// @param data plainobject (optional)
function ajax(url, success, method, data) {
var xhr = new XMLHttpRequest();
// Set the callback to use when all the stuff is done
xhr.onreadystatechange = function() {
// We are not interested in the 3 other stages
if (xhr.readyState == XMLHttpRequest.DONE) {
success(xhr.responseText)
}
}
// Open using the provided method or 'get' if none
xhr.open(method || 'get', url, true);
if(method == 'post') {
// Set the content-type in case of post
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
if(data) {
// Build data string if something is provided
var res = [];
for(var k in data) {
res.push(encodeURIComponent(k) + '=' + encodeURIComponent(data[k]));
}
data = res.join('&');
}
// Send the request to the server using the provided data
xhr.send(data);
}
// Examples
ajax('test.json', function(data) {
console.log(JSON.parse(data));
});
ajax('index.html', function(data) {
console.log(data);
});
ajax(window.location.href, function(data) {
console.log(data);
}, 'post', { 'test' : 'yoh' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment