DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Mini AJAX

05.15.2006
| 73190 views |
  • submit to reddit
        <strong>Update: This code, along with docs and tests, are now available at <a href="http://github.com/seven1m/mini">http://github.com/seven1m/mini</a>.</strong>

A handy, lightweight set of AJAX functions.

function $(e){if(typeof e=='string')e=document.getElementById(e);return e};
function collect(a,f){var n=[];for(var i=0;i<a.length;i++){var v=f(a[i]);if(v!=null)n.push(v)}return n};

ajax={};
ajax.x=function(){try{return new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){return new XMLHttpRequest()}}};
ajax.serialize=function(f){var g=function(n){return f.getElementsByTagName(n)};var nv=function(e){if(e.name)return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);else return ''};var i=collect(g('input'),function(i){if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)});var s=collect(g('select'),nv);var t=collect(g('textarea'),nv);return i.concat(s).concat(t).join('&');};
ajax.send=function(u,f,m,a){var x=ajax.x();x.open(m,u,true);x.onreadystatechange=function(){if(x.readyState==4)f(x.responseText)};if(m=='POST')x.setRequestHeader('Content-type','application/x-www-form-urlencoded');x.send(a)};
ajax.get=function(url,func){ajax.send(url,func,'GET')};
ajax.gets=function(url){var x=ajax.x();x.open('GET',url,false);x.send(null);return x.responseText};
ajax.post=function(url,func,args){ajax.send(url,func,'POST',args)};
ajax.update=function(url,elm){var e=$(elm);var f=function(r){e.innerHTML=r};ajax.get(url,f)};
ajax.submit=function(url,elm,frm){var e=$(elm);var f=function(r){e.innerHTML=r};ajax.post(url,f,ajax.serialize(frm))};

<strong>How to use:</strong>

<strong>ajax.x</strong> - The XMLHttpRequest object (or MS equivalent) used for communication

<strong>ajax.serialize(f)</strong>
<em>f</em> = the form element you wish to be serialized
This function serializes all the fields in a form so that they can be passed as a query string in the form "arg1=val1&arg2=val2".

<strong>ajax.get(url, func)</strong>
<em>url</em> = the url to query (can contain arguments after a '?')
<em>func</em> = the function to call once the response is returned
This function uses a GET request to query the specified url and return a response to the specified function.

<strong>ajax.gets(url)</strong>
<em>url</em> = the url to query (can contain arguments after a '?')
This function uses a GET request to query the specified url and return a response synchronously. Use this sparingly, as synchronous calls can lock up the browser.

<strong>ajax.post(url, func, args)</strong>
<em>url</em> = the url to query
<em>func</em> = the function to call once the response is returned
<em>args</em> = a string containing arguments to be passed to the url
This function uses a POST request to query the specified url and return a response to the specified function.

<strong>ajax.update(url, elm)</strong>
<em>url</em> = the url to query
<em>elm</em> = the (name of the) element to update
This function uses a GET request to query the specified url and insert the result into the specified element.

<strong>ajax.submit(url, elm, frm)</strong>
<em>url</em> = the url to query
<em>elm</em> = the (name of the) element to update
<em>frm</em> = the form element to submit
This function is typically used in the onsubmit handler of a function. The form is not submitted the usual way; the form is instead serialized using "ajax.serialize" and submitted using "ajax.post". The result is then inserted into the specified element.    

Comments

Snippets Manager replied on Fri, 2009/05/29 - 1:12am

Ajax.serialize has problem with select of some browsers: select's value is not availabel and should be accessed by selectObject.options[selectObject.selectedIndex].text. Here is an alternative: Ajax.serialize=function(f) { var g=function(n){return f.getElementsByTagName(n)}; var nv=function(e){if (e.name) return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value); else return ''}; var nv2=function(e){if (e.name) return encodeURIComponent(e.name)+'='+encodeURIComponent(e.options[e.selectedIndex].text); else return ''}; var i=collect(g('input'),function(i){if((i.type!='radio'&&i.type!='checkbox')||i.checked)return nv(i)}); var s=collect(g('select'),nv2); var t=collect(g('textarea'),nv); return i.concat(s).concat(t).join('&'); }

Snippets Manager replied on Tue, 2009/02/24 - 4:44pm

very good article, you really have a smooth way to deliver information, thanks for the clear efforts your making. free games

Snippets Manager replied on Mon, 2012/05/07 - 2:23pm

Dave, I have moved dev of this library to GitHub, http://github.com/seven1m/mini where I also have the non-compressed version of the library. I'll see if I can get your code in there soon.

Snippets Manager replied on Fri, 2009/02/06 - 8:24pm

The solution I just worked out uses the following (ugly and bulky) : //////////////////////////////////////////// if(e.multiple){ var rs = []; var tot=0; for (var i=0; i < e.options.length; i++ ) { if( e.options[i].selected){ rs[tot] = e.name + '[' +tot+ ']=' + encodeURIComponent(e.options[i].value); ++tot; } } return(rs.join('&')); }else{ return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value); } ///////////////////////////// It replaces the "return encodeURIComponent(e.name)+'='+encodeURIComponent(e.value);" part of the "nv" section of the ajax.serialize() function. Does anybody want to do a better job with the coding (than I have) and integrate this back into a nice compact copy and paste version like the other posts?

Snippets Manager replied on Fri, 2009/02/06 - 8:24pm

Yes, I send the output from submit (which calls serialize) to a php script which used to accept multi-selections if the "name" attribute was assigned a name with "[]" at the end. But its not that simple using a plain old non "submit" type button and MiniAJAX. (O.T.: also broke my file upload functionality.. but that's not as much of a surprise). So it doesn't seem like it would be that hard. Perhaps I'll add a function to collect the multiselect options and stuff them into a string that could then be passed like the rest of the miniAJAX variables.

Snippets Manager replied on Mon, 2012/05/07 - 2:23pm

Are you referring to the serialize method? Does it not work for a multi-select lists?

Snippets Manager replied on Fri, 2009/02/06 - 8:24pm

I'm loving this code too. But, is there any chance that any body here is interested in making it work for multi-select boxes? I'm probably going to start trying to add this functionality myself tomorrow.

Snippets Manager replied on Wed, 2008/02/27 - 2:28pm

@fatih_kadir_akin Thank mate. I absolutely LOVE this .JS file. it's the most useful file on my site. And now that it's got JSON support, that just solved my current work. I was just discovering the usefulness of JSON, and was just coming here to download the miniAJAX.js again ... and found it now has JSON support :) :) :) :). Thanks be to [fatih_kadir_akin] and [timmorgan]

Snippets Manager replied on Mon, 2012/05/07 - 2:23pm

I like your nocache stuff. I had actually done that myself in some of my apps due to IE caching stuff. I will probably update the get and put methods to tack that on since I believe that should be the default behavior.

Snippets Manager replied on Wed, 2008/02/27 - 2:28pm

well, started a new thread for this and updated it again. this time for "parse" ability. check it out at: http://snippets.dzone.com/posts/show/5182

Snippets Manager replied on Wed, 2008/02/27 - 2:28pm

PS - the noCache versions just tweak the passed URL with: u = u + (u.indexOf('?') < 0 ? '?' : '&') + new Date().getTime(); which just effectively adds a new query parameter of some fairly random digits. They don't need a "name" or a "value" to work, but if you want you can change the code to: u = u + (u.indexOf('?') < 0 ? '?' : '&') + 'noCache=' + new Date().getTime(); this way it's a bit more obvious in the called URL what is happeneing with the gibberish, so you see something like: /_subpage1.jsp?param1=abc&param2=def&noCache=1204137560531 but without the words "noCache" it still works but is shorter: /_subpage1.jsp?param1=abc&param2=def&1204137560531

Snippets Manager replied on Wed, 2008/02/27 - 2:28pm

very nice code. i've adapted it a little to handle for IE's stupid Caching issue when using AJAX: function $(e){if(typeof e=='string')e=document.getElementById(e);return e}; function collect(a,f){var n=[];for(var i=0;i I simply added the following functions: ajax.sendNoCache(url,func,method,args), not called by user, but called by some below functions. ajax.getNoCache(url, func) ajax.getsNoCache(url) ajax.postNoCache(url, func, args) ajax.updateNoCache(url, elm) ajax.submitNoCache(url, elm, frm)