Last active
August 29, 2015 14:17
-
-
Save bendem/c5a038e0045470a5e50f to your computer and use it in GitHub Desktop.
This file contains 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
// 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