Simple AJAX Function with Example

Below is the simple AJAX function that I use in many of my projects, TinyAjax. It makes it easy to call and process GET and POST transactions. Here are the parameters:

  1. URL (required)
  2. ID of the output element (pass a zero/false for no response output)
  3. String of function to be evaluated and called on completion (optional)
  4. Post content – example: id=22&action=1 (optional)

I will be posting more small snippets soon as well as some updates to previous scripts, new code, and tutorials. Last year was roller coaster with getting my business off the ground and it shows in my lack of time for this site. That being said, I plan to take more time to give backĀ  this year and grow my own skills so expect to see much more of me on here. I cleaned up the forums and implemented DISQUS to help everyone get the most out of this site.

On a side note, I have formed a new company this year with a partner and we are opening an office in historic downtown Franklin, TN. We will be looking for some good people to work with us so if you or anyone you know is in the Nashville area, please have them drop me a line.

TINY={};

function T$(id){return document.getElementById(id)}

TINY.ajax=function(){
    return{
        call:function(u,d,f,p){
            var x=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
            x.onreadystatechange=function(){
                if(x.readyState==4&&x.status==200){
                    if(d){
                        var t=T$(d);
                        t.innerHTML=x.responseText
                    }
                    if(f){
                        var c=new Function(f); c()
                    }
                }
            };
            if(p){
                x.open('POST',u,true);
                x.setRequestHeader('Content-type','application/x-www-form-urlencoded');
                x.send(p)
            }else{
                x.open('GET',u,true);
                x.send(null)
            }
        }
    };
}();

A call would look something like the following:

TINY.ajax.call('get.php?id=32', 'content', 'display("red")'); // GET
TINY.ajax.call('post.php', 'content', 'display("green")', 'id=32'); // POST

Click here for the demo.

Click here to download a fully working example in PHP.

Keep in mind that this will not work on your local computer unless you are running a web server like Apache. This script has been tested in all major browsers and is available free of charge for both personal or commercial projects under the creative commons license. Community support is available here.

This entry was posted in AJAX, JavaScript, Syndicated. Bookmark the permalink.

Comments are closed.