This is a quick little snippet of AJAX for you eager users out there. It is cross-browser compatible, and is definitely some of the cleanest code available. var xml = createXML(); var el = new Array(); function createXML () { if (typeof XMLHttpRequest == 'undefined') { xmlObjects = Array( 'Microsoft.XmlHttp', 'MSXML2.XmlHttp', 'MSXML2.XmlHttp.3.0', 'MSXML2.XmlHttp.4.0', 'MSXML2.XmlHttp.5.0' ); for (i in xmlObjects) { try { return new ActiveXObject(objects[i]); } catch (e) {} } } else { return new XMLHttpRequest(); } } function get (id) { return document.getElementById(id); } function getPage (url, element) { el['results'] = get(element); xml.open('get', url); xml.onreadystatechange = function () { if (xml.readyState == 4) { el['results'].innerHTML = xml.responseText; } else { el['results'].innerHTML = 'Loading…'; } } xml.send(null); } function postPage (url, parameters, element) { el['results'] = get(element); xml.open('post', url); xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xml.onreadystatechange = function () { if (xml.readyState == 4) { el['results'].innerHTML = xml.responseText; } else { el['results'].innerHTML = 'Loading…'; } } xml.send(window.encodeURI(parameters)); } Code (markup): If you enjoyed this code please feel free to leave rep or comments (maybe both )
Yes thats a clean and easy to use code, but you should also post some code usage example for newbies here.
this is nice code... but i guess it will confuse newbies more ... try and put lot of comments and sample usage ... i hope after this you will get some good green reps
Basically, with this code you can post variables to server and can catch response returned from server. I will try to post a practical implementation of this code tonight.
Thanks for sharing. I'm taking up learning Ajax myself actually. Hopefully I'll find a good book soon, it's nice to have a print book when learning any scripting or programming.
Hey TheException, but I think a short practical example or case study teaches you what you learn from 25 or 30 pages of book.
I guess: return new ActiveXObject(objects[i]); Code (javascript): Should be: return new ActiveXObject(xmlObjects[i]); Code (javascript):
There goes my tutorial on this http://www.hakc.net/2007/02/15/the-hello-world-ajax-script/ Code (markup): Hope it's good and well explanatory!
Gimme my thread back Thanks for all the comments and suggestions, guys! Sorry about the minor code error, check out nico_swd's post on the fix Thanks, Nick