A handy AJAX func

+2 Jason Knight · March 7, 2015
Something I noticed in the forums is that making AJAX calls seems to be a reoccurring issue for people and people turn to the jquery library just for ajax request's ... so i posted this function to my wall and it was suggested to move it here, so here it is.


function ajax(args, callback){ 
var hr = new XMLHttpRequest(), 
contentType = (typeof(args.contentType === 'undefined')) ? 'application/x-www-form-urlencoded' : args.contentType;
 
hr.open("POST", args.url, true); 
hr.setRequestHeader('Content-type' ,contentType ); 
hr.onreadystatechange = function() { 

if(hr.readyState === 4 && hr.status === 200) { 
var return_data = hr.responseText; 
if(return_data){ 
callback.call(this, return_data); 


}; 
hr.send(args.vars); 
}; 

This function takes two arguments 
1. a JSON array with the params url : // the url you want the vars to be posted to, vars: // the varibles that are being sent. eg action=test&message=hello and finally contentType // this is an optional param and should be left out unless you need to change the content type for the post

the second argument is a callback function that will be fired if the post has returned any data from your server. 

the function  can be called like so 


ajax({ 
url : 'http://localhost/myproj/test.php', // the url you are posting to 
vars : 'action=test' // your post vars 
contentType : 'yourcontenttype' // optional just leave out if you dont need to change the content type 
}, function(data){ 
//this is the callback fired of when post is complete 
alert(data); 
});

This has served me well and done what i want it to do for a while now but as Samuel Oloruntoba mention this could also return a promise, with a bit of modification which you'll be familiar with if you've used a couple of popular node repos. 
if you'd like it to return a promise here is a break down of promises http://www.html5rocks.com/en/tutorials/es6/promises/

Post a Reply

Replies

Oldest  Newest  Rating
+1 Jason Knight · March 7, 2015
I understand where you are coming from but i posted this because on just about every page people are having trouble with AJAX, then just resorting to jquery when it is not needed. they are obviously beginners in need of help, and to me it made alot more sense to post a forum post, then to go through every question now and in the future or to post a gist on github which beginners may not even be aware exists yet, if an admin find's this inappropriate they are welcome to remove this post and i wont take it personally but these forums are here to help beginners.
  • 1

Javascript

107,204 followers
About

A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.

Links
Moderators