Instant AJAX Tutorial
After taking a look at this AJAX tutorial and a couple others, I was disappointed at the quality of the code so here’s a quick tutorial to get you jump started with AJAX (Asynchronous JavaScript + XML). I am using object detection and explain some of the caveats for doing what I am doing.
Simply put, AJAX allows you to make a call to an http server (typically an RSS feed or a webpage), get its content and load them into your existing page without having to refresh the whole page. This means that services like email don’t have to reload the whole page every time you click a message, saving on bandwidth (loading the header/footer all over again) and making things more efficient.
On to the AJAX code:
function loadurl(dest) { try { // Moz supports XMLHttpRequest. IE uses ActiveX. // browser detction is bad. object detection works for any browser xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // browser doesn't support ajax. handle however you want } // the xmlhttp object triggers an event everytime the status changes // triggered() function handles the events xmlhttp.onreadystatechange = triggered; // open takes in the HTTP method and url. xmlhttp.open("GET", dest); // send the request. if this is a POST request we would have // sent post variables: send("name=aleem&gender=male) // Moz is fine with just send(); but // IE expects a value here, hence we do send(null); xmlhttp.send(null); } function triggered() { // if the readyState code is 4 (Completed) // and http status is 200 (OK) we go ahead and get the responseText // other readyState codes: // 0=Uninitialised 1=Loading 2=Loaded 3=Interactive if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) { // xmlhttp.responseText object contains the response. document.getElementById("output").innerHTML = xmlhttp.responseText; } }
The above code goes between the html <head></head> tags. The corresponding html body would be:
<body> <div id="output" onclick="loadurl('/resume/resume.txt')">click here to load my resume into this div</div> </body>
The destination URL for an AJAX request has to be in the same domain or a security error might be thrown depending on your security settings.
Here’s a working example (it loads my resume):
Great tutorial! I do like this better than the 30-second tutorial. Nice introduction to how the engine works.
Wow, I had no idea it was that easy!
help!
I am trying to do the AJAX thing, I use ASP all the time, now I want to do a simple input form that would call an ASP page to do a database search based on the form field. Then the ASP file I called would display the results.
How can I use AJAX to display the input form and display the results, while using ASP to do the database search stuff?
Thanks,
Nice tutorial. It was very usefull and easy to understand. Thanks a lot !
excellent tutorial. you wouldn’t believe how confused i was about AJAX until i read your tutorial. this morning i had no idea how to do it, by the afternoon i’d moved one of our frequently used dynamic pages (a phone book search) over. the difference in performance is amazing!
i still can’t believe how easy it was to implement once i grasped the concept. it’s like a huge flashbulb just went off in my head.
thanks again for the execellent tutorial!
Can some one please explain this:.. How come you are calling the triggered event first?.. This looks like we are updating the output div prior to sending the xmlhttp request?.. i know i am wrong.. this is why i am confused.. could someone help?
Thanks,
xmlhttp.onreadystatechange = triggered;
xmlhttp.open(“GET”, dest);
xmlhttp.send(null);
To Saeed Saeed :
xmlhttp.onreadystatechange = triggered;
This doesn’t call the trigger() function, it just tells the xmlhttp object the name of the function to call when the status changes.
Note the lack of parentheses at the end of the function’s name.
dont worry about my previous question, i wasnt setting up the head data. i’ve now got a “gracefully degrading AJAX form” demo up at my site, it’s very clunky at the moment, more a proof of concept than a nice neat example like this is. it’s got four levels:
1. full DOM + AJAX
2. basic DOM styling
3. basic javascript
4. classic page reload asp
each level magically works on a number of browsers (but my test list is by no means extensive) including good old text based lynx.
anyway, i think there’s plenty of scope for enforcing the doctorine that accesability is king and forcing a page to only work with ajax causes bad juju.
http://www.cyclomedia.co.uk/ajax_degrade.asp
Is it possible to make the page that AJAX generates auto refresh to pick up any new content?
Dear Aleem!
Nice stuff but let me tell you one thing or maybe you already aware of it that,AJAX dont work on cross domain,that is XMLHTTP object gives you permission error if your server side code is on other domain.Its default browser settings for sake of security.
I needed to implement CONTACT page on my blog at Blogger.com which dont allow me to do any customization on serverside,i decided to make contact form by using ajax,since i was not allowed to do it due to behaviour of xmlhttp,therefore after research of 3-4 days i found a php library which uses proxy technique to fetch data,details are on my blog post:
http://kadnan.blogspot.com/2006/01/customized-ajax-based-contact-form-for.html
and you can check Demo at http://kadnan.blogspot.com/ or on my free geocities page:
http://www.geocities.com/kadynan/ajax-geo.html
you may also integrate it for your any site for demo purpose
regards
Adnan
Shadow!
yes it is make a function which instantiate xmlhttp object and call that function in settimeout method.
Aleem!
Nice tutorial!one of the problem with AJAX is that it doesnt work on cross-domain.i got a PHP based library which doesn`t use xmlhttp object to fetch data and works fine with bote iE and Firefox,most important it works on cross-d0main as well,i made a Contact form which is ajax based and can be used with anysite even like geocities where you dont have access to work on php and other languages.check this out on my blog(http://kadnan.blogspot.com), my Contact Me form is live example of it,installation details also mentioned in one of the posts
-adnan
Thank You for your great tutorial. It helped me a lot!
Ever though about using prototype? It’s such a more practical way of doing this type of coding. Well done though …
The tutorial is nice, and does a great job in defining what AJAX really is. Although it doesnt exactly give an idea, the power of AJAX, and what it can do.
I couldn’t try this. Could you post the apsx file?? I can’t get the code in the head section to execute. It just displays in the page. Obviously I’m a newbie. Thanks.
As a total newbie to Ajax, I want to use this amamzing tech to use on one of my pages here: http://www.rpgvillains.com/index.php?pagina=music
Basically I want the music table to reload using ajax each time I click on a corresponding letter. I tries it already but didn’t work yet. Anybody can help?
Thanks alot 🙂
It works great with my .txt .htm and some .asp files… However it won’t return some of my .asp pages… any help would be great thanks
I must be missing something???
I have a lightbox script on my main page that works perfect, but once the LoadURL goes through, no code on the included url works for that lightbox, any ideas?
Lightbox (the original version) doesn’t play nice with any type of code displayed within it. It was made as a slideshow function, and that’s all-if you want to load a page within it, you need to try something like one of the alternatives (I use Lightview).
Excellent starter for AJAX. What I need to do if the onclick event is outside the box to refresh. If anyone could help asap, plesae….
I got the resulr use a where you want to see the output and use where you wanna set the clickable link, that’s easy…
Use a div tag with id=”output” where you want to see the output and use div with onclick=”loadurl(“xxxx”) where you wanna set the clickable link, that’s easy…
Hi,
I have to do a part in ajax on my asp page. I’m new to ajax and asp.
On an asp page i want to display a list of items that are added at run time.
Display should be like a grid where i can delete the record or add a new record but i dont know hw to start with this on asp page, help me out.
Thanks
leela
hey there
great tutorial … but can anybody help me (Iive not much anticipation in js/ajax) and modify the script about a function to close reloaded content or get the aboriginal content back respectively.
ex:
link – close
you klick on the “link” – it loads content, you click on closed – it closes the content.
and … it have to be possible to to reload different content on different places on the website and also closed them separatily.
i would be very happy about that
great thank
gr33tz, schrecke
Hey, can somebody help?
I’ve been pulling my hair out trying to get my XMLHttp request object to work!
Every time I try to call the object.responseText (even when I copy the example above) there is no repsonse. In firefox the error reads-
“Error: syntax error
Source File: file:// – URL of .txt here –
Hello World!”
I’m working through Ajax for dummies at the moment and all of the examples from the book have the same problem, none of them will work.
Any clues?
thanks
@Gavin
“Error: syntax error
Source File: file:// – URL of .txt here –
Hello World!”
that sounds to me like you are not using the right path to the file to load, post your code to take a look at it
hi,
i wanna know that how i use ajax with ASP.net 2.0?should i have to download an API of AJAX or something else have to be done in order to use AJAX?
I was wondering if it supports urls like something.com/page.php?id=1
I tried it, it loads the page but without sending the GET variables. it is “?id=1” was never there.. any ideas?
try this…
Using a div
function displayText(txt)
{
document.getElementById(“targetDiv”).innerHTML = txt;
}
Using a div
i interchanged the single quotes with the double quotes, and it worked for me…….
yes it is make a function which instantiate xmlhttp object and call that function in settimeout method.