Simple AJAX Function with Example

Javascript 26 responses so far

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 PHP example.

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.

The following two tabs change content below.
Scriptiny is a web development blog featuring fresh articles on JavaScript, AJAX, CSS, XHTML, PHP, Photoshop and more.

Latest posts by Michael (see all)

  • Abbe

    Very nice, thanz for sharing,
    I was hoping to finde here a tiny tabbed pages and a tiny folder tree.

  • Anonymous

    I will add those to the short list.

  • Signale

    Wait a second, there are a lot of such stuff(lightweight tabs and folder tree), why wasting the time???

  • Abbe_vallipour

    I have done a lot of searching on the internet, the smallest folder tree I found was over 20 Kb and tabbed pages was over 10 Kb and it does’nt remember the active TAB, and both poorly written, I am suggesting leigeber to add his lightweight version of those tools since there already are tools here, like TinyFader and dropdown menu, that can be modified to behave like TABs and folder tree.

    Thanx :)

  • http://www.eluminoustechnologies.com/ web development services

    Incredible topics are included in this blog.Add more in future,Thanks.

  • Wordpress Shopping Cart

    Thank you for posting such thorough information for free. So many sites I find are charging people. Keep it up!

  • Mike

    This approach, which is common, creates memory leaks in IE. This happens every time you have a self referencing activeX control in IE. Also, IE7's XMLHttpRequest object will error out when working locally, but the activeX component in IE7 will not. So it may be better to initialize the activeX component in IE7 if it is being used locally instead of the XMLHttpRequest.

  • Mike

    How dojo(as well as jQuery and most frameworks) overcome the memory leak.
    http://infrequently.org/2005/12/file-uploading-with-dojo/

  • http://web.kentostudios.com Kentostudios

    thanks

  • Steve

    Is it possible to pass a javascript variable to "id=32" ?   I have a dropdown select listbox and I would like to select an option from the dropdown and then send that and then retrieve that same option. For example, the dropdown may have id's of 29, 30, 31, 32 and 33.  If I select id 31, then the ajax sends id=31   instead of id=32 being hard-coded.   Thanks

  • Keith

    Very Nice

  • Alisha Saim
  • http://www.maxiaodong.com stone crusher

    Thanks for your sharing

  • http://twitter.com/Wysoho Wysoho

    Thanks..very much for sharing..;)

  • John12

    good

  • adumpaul

    Nice post.Ajax function is nicely work.

  • http://www.adsyou.com/ شقق للبيع في الاردن

    If I select id 31, then the ajax sends id=31   instead of id=32 being hard-coded.   Thanks

  • hrtyt

    texff

  • Mitch Turner

    sweet

  • Shiva

    It is very nice and useful for me…..
    Thank you…

  • http://www.cyberdesignz.com/services/custom-web-designing Custom Web Designing

    Great post that helps me a lot in my project. These function work nicely and Thank you so much for sharing your experience with us. Great work.. 

  • rickystephen123

    nice.

     <a href="http://www.webintechs.com/web_designing.php">professional website designers</a>

  • Annamalai

    Too gud……i luv this script..very useful for large scale applications…thanks dde

  • GinoB

    Many thanks! Is it possible insert an loading image?

  • Phan Mem CRM

    Thanks for sharing

  • capricorn

    Nice work…….