Easy Ajax with Prototype
69 Comments
Comments are ordered by helpfulness, as indicated by you. Help us pick out the gems and discourage asshattery by voting on notable comments.
Got something to add? You can leave a comment below.
Drew McLellan
Mike Ward
OK, I’ll be the first to admit that I am one of those ‘Javascript is to hard’ people, but I know a good deal when I can get it. Since I am just starting to dable in .php, I am wondering if this can be done in .asp just as easily.
Anyone? Bueller?
Thanks
Ashley Bowers
You are truley amazing. I can not wait to see what my friends and co workers have to say about this new script! Three cheers for Sam for develpoing this awsome javascript!
Henrique Costa Pereira
OH OH OH… Thats great! But I not sure about SEO technics and AJAX! Someone can tell me a trick?
Joe
Fun!
Not to be a Grinch, but for the form to work without Javascript, the input has to be changed:
input name="greeting-name" id="greeting-name" type="text"
Marko Mihelcic
I didn’t read a good article like this in a long time. Thank you.
James
I’m new to using Prototype and have a quick question. If, in your example, I change the id=”greeting” to an input box with the same id, instead of a textbox, it doesn’t work.
Do you have to do something special on form elements for information to get returned into it?
Sopan
Hi,
I remove the the script “greeting.php” from the html page -.i.e. from line
form method=”get” action=”greeting.php” id=”greeting-form”
Still your echo stuff works. I dont think this server side scipt is used by your ajax application.
I tried puting different – script names which gives different output.. i dont think your ajax application deals with server side script..
In Any case – document is good written.
—sopan
Balakumar Muthu
That’s really a C-O-O-L tutorial on AJAX!! :), I like it, very good for all newbies!!
—Balakumar Muthu
http://i5bala.blogspot.com
Ben Scott
think this technique would be perfect for w3c schools page suggest it to them so they can be more interactive
Alex Beston
btw – as an aside – how do you get the image in the left most of the connent? like what rutter has. ta
Alex
MS
Thanks
Philippe Jadin
Why not simply post the content of the form to an iframe located where the div is?
No javascript…
Aaron Gustafson
Nice one Drew. What’s next? Rudolph on Rails?
Tom Martin
Rudolph on Rails, brilliant.
sbrewer
Mike, the asp equivalent of the php file should be something like:
@
Dim the_name the_name = Server.HTMLEncode(Request.Querystring(“greeting-name”)) Response.Write(“Season’s Greetings, ” & the_name & ”!”)@
Stringer
I’m using Prototype 1.3.1 and it seems that the behaviour after pressing the enter key is different on my server than the example provided.
On my server after pressing the enter key it displays:Season's Greetings, !
Whereas when I try the example it displays:Season's Greetings, Stringer!
Any ideas why? Perhaps it’s my version of PHP?
Jens Meiert
Very good, and it should finally clarify why Prototype is that useful!
Daniele Florio
We have developed a function that use AHAH that sends form parameters in GET or POST format.
If you want to see, here the example:
(1). http://www.gizax.it/experiments/AHAH/
for download
(2). http://www.gizax.it/experiments/AHAH/form.zip
bye bye,
Daniele
Jeremy Kitchen
This article is a good example of how helpful prototype is when developing AJAX-ified applications, thank you for sharing it :)
You should use encodeURIComponent(), rather than escape(), as escape is deprecated in EMCAScript v3 (according to O’Reilly’s “Javascript: The Definitive Guide”, 4th ed.)
-kitchen
Pete Freitag
Thanks for this tutorial!
DMZ
the following code is giving me a runtime error in IE 6.0 in Win XP:
Event.observe(window, 'load', getOptions, false);
function getOptions(){
var url = 'Query.cfm';
var pars = 'group='+escape($F('Select'));
var target = 'Options';
var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars});}
any ideas? from what i can tell the line giving the error is the last line of the block that starts with if (receiver) {
under the block that starts with updateContent: function() {
Options
is a div, Query.cfm
generates a select menu. Help!
Richard Rutter
Web 2-point-HoHoHo
ROFL – I nearly spilled cornflakes all over my iBook – that really tickled my fancy. It’s Web 2-point-HoHoHo all the way through December for me.
Great little article btw Drew, and a great idea for a seasonal blog. This’ll give me something to play with while the family falls asleep in front of the Queen’s speach.
Alex Beston
is this the most easy way to do ajax? Ive been playing about with my own rolled code and after a few days i had ironed out alot of the problems. thing is, its great for prototyping (hence the name?!) but as a coder i dont get that satisfaction of making inventing my wheel as it were. still, RoR is the way to go and this is a great introduction methinks
Jeff Croft
Philippe Jadin-
Posting the form to an iframe is by no means the same thing. Posting the form to an iframe:
1. Requires the user to click the submit button.
2. Does not update on every keystroke.
3. Requires you to use an iframe, which is not a valid element in XHTML Strict.
Of course, posting the form to an iframe might be an acceptable solution in many cases, but it certainly does not offer what AJAX does.
Drew McLellan
Joe – yes, you’re right. You’d need to hook the form up in the usual way. For my own testing I actually passed an extra parameter with the Ajax call to indicate that it was Ajax – then used the same page (in two different modes) to give the results to both Ajax and a regular form submission.
Philippe Jadin – this is just a really basic example to help readers get their feet wet with Ajax. Of course there are other ways of doing something as simple as this. It’s when you get into the real-world use cases for Ajax that it becomes clear how much more flexible it is than a simple iframe.
Phil
I’m new at prototype and Ajax. Nice article.
Question: If I wanted to make my server side response into a boring string, with no HTML formatting, and let the ajax.js JavaScript functions turn that string into HTML w/ the P tags around it, would I use the Ajax.Request class instead, and use the onComplete: myFormatStringAsHtml option? Am I going in the right direction with that, or can the .Updater class call a function instead of inserting it’s result into a DIV?
I found a couple of sites with prototype docs but not many complex exmaples. It would be neat to see (or figure out and write if I had time) a series that started simple and got more complex. Pointers to good articles/docs would be appreciated.
ph0tik
Exactly, I can’t understand why you gave the code and no demo. Impress me! haha
Drew McLellan
Since you asked so nicely, I’ve added an example.
Of course, this particular example doesn’t need Ajax to achieve the effect. The exact same could be done with regular client side JavaScript alone. However, that’s not the point. The idea here is to get your toes wet with a little dip into the Ajax waters.
That sounded kind of gross.
Drew McLellan
Stringer – have you checked your form is GETting and not POSTing?
The example script does go a step further than the code above in making sure a full document is returned for non-Ajax calls. This is done by looking for the Submit button in the GET. But that should have no impact on the name coming through.
Haochi
That is kinda wired.
Alistair
Are people writing higher end frameworks utilising Prototype or is the general movement to just use Prototype and then add glue?
Al.
Prem
I`d also like to know on how we can use the POST method with the prototype.js
does anyone know?
Richard Brown
Thanks, I’m also new to the Ajax. I’m about to start a new developer job (after a year of doing only networking). Anyone have a suggestion for a good Ajax book?
tremendo
Richard, suggestion for a good Ajax book:
http://www.pragmaticprogrammer.com/titles/ajax/
Andrew Urquhart
A few months ago I had to implement something similar for my place of work (sorry, closed source). This used ordinary forms and hyperlinks and a DOM walker attached to the onload event. When the DOM walker found a form with a custom class attribute on it it attached an onsubmit handler. Submitting the form caused the handler function to hijack the form submission. All of the successful controls in the form were parsed, URL encoded and assembled into keys and values and submitted to the original form action URI, but as a HTTP request instead. A hidden input field indicated the element id to populate with the result.
A similar mechanism for hyperlinks used structured rel attribute values that worked in a similar way, except that it allowed you to submit hyperlinks (with querystrings) by AJAX POST (as well as GET) requests and include space for application/x-www-form-urlencoded POST data! More about this at http://andrewu.co.uk/webtech/comment/?easy_ajax_with_prototype
Brian Schwartz
Very nice. I was always a bit scared to divulge in AJAX – this is a great place to start
Bacon
One thing I noticed though, it doesn’t update when you paste something in the text field.
Not that it’s a problem, I’d rather use an onblur instead of a keyup anyway.
Great artical nonetheless :)
Joe W.
You need to remove the backslashes in the example of your PHP script.
Possible patch:
$the_name = htmlspecialchars(stripslashes($_GET[‘greeting-name’]));
Actually, if this is a script you’re gonna share across other servers you should probably check what the magic_quotes setting is before stripping the quotes.
Steve
Bacon, try onChange() instead.
Jim Amos
But if I hit the back button after your demo in Safari (1.3 Panther) the browser window farts and crashes.
Mark
Whoa – Prototype sucks compared to Sajax. I’ve been using Sajax for a couple months and it’s a breeze. It’s as flexible as anyone should need for most stuff. Definitely worth a look if you’re touting Prototype as something special.
http://www.modernmethod.com/sajax/
Mel
Just to combat the inevitable rush of “Prototype sucks, use foo instead!” comments, one needs to understand that Prototype is by no means a well-rounded AJAX library, but more a good I-do-a-lot-of-Javascript library.
e.g. $(‘bar’) == document.getElementById(‘bar’)
I would seriously recommend Prototype or MochiKit to those of us who need to hack at Javascript and something like Dojo for those seeking a more complete solution.
gus
how do i send 2 different parameters to my php script with one function?
Scrambled
How about some server-side validation done client side :) like this
Credit where its due: This is based on ParticleTree’s validation script but much amended; they also have a guide to prototype
Rob
I’ve been using the prototype library for a while now – it’s great!
Thanks for the primer – I’ll send it to a few friends who want to dip their toes in the ajax waters!
devang gurjar (devdatt)
great article
Mr. Khmerang
Nice introduction! Though I have issues with it on slow connection. Some events don’t seem to get through if I’m typing stuff fast and it leads to having different text in the textbox and the div.
For something completely different, the tab order of this form seems to be a bit strange (FF1.5 on IE)? Jumps from http field to top top of the page.
Sopan
Sorry, It works correct, I forgot to notics “greeting.php” script name in ajax.js file.
jaime
how do i begin a web page?
Don Zacharias
way cool, but as far as i can see there is no div with the ID output-div on your html page sample. is that supposed to be target = ‘greeting’?
not trying to nitpick, just a newbie trying to hork this web2.0 goodness…
Andre
I would like to see an similar example with Coldfusion if possible…
Justin Perkins
Great example, thanks a lot. HTTP requests and responses going back and forth after every keystroke is scary though. Note to newbies, don’t do this in a real app.
Daniele Florio
Example of Degradable LiveSearch in AHAH
http://www.gizax.it/experiments/AHAH/degradabile/test/liveSearch.html
Petit
Hi!
Terrific tutorial for a beginner to start off with!
X-tal Clear.
ThanX & Merry X-mas!
Clint Lenard
Nice Tutorial! I learned quite a bit in such a short amount of time. :-)
wahyu
any idea how to update a dropdown box after the other dropdown box is changed?
I use prototype for this. I have the php script which output the results in html (looped by php). The other page uses ajax prototype with ajax.updater and ajax.insertion, but it just put the results as normal text without the html part. Is there any special extension for populating that kind of dropdown box with prototype? I tried the documentation from http://www.sergiopereira.com/articles/prototype.js.html but not all of the extension has at least an example. Thanks
Mayuresh Kadu
louis w
i have always been interested in Prototype, nice article. my only criticizem with prototype is that is comes with no documentation and no examples. which is why i have never gotten around to installing it.
toanyeah
Greet tutorial for beginners like me, but I wonder why changing the method to post makes the text display slowly. Thanks again and hope to see your new tutorial, happy holidays
Vital
nice, but it not work and generate many errors in incompatible browsers, like IE5.0.. :(
Si
Thanks for that little ditty. I’ve not read a good article about the prototype.js script yet and this article was the first time I’ve read and understood its capabilities.
Hopefully that should sway my peers at work into taking AJAX on now.
(BTW, it’s always good to keep some real Ajax handy during the festive period. You never know when you’ll need to clean up some unexpected spillages with all those damn kids around!)
Alex Beston
hmm – looks good!
Drew McLellan
Alex – check out gravatar.com
me
So, this whole AJAX thing … not sure I’m interested in it. Maybe, though. It does seem like it could be useful in some applications. But, why haven’t you included a demo of what this code does? I’m the type of person that needs to see if this is what I need before I dig into the code and re-write in my own application.
Show us an example of what the code does, please!!!
Mart
This is great. Its works like charm. Thanks.I cant wait till christmas now, roll ‘em on … ;)
Paul Beardsell
Does anybody have any Ajax and Coldfusion examples?
Andrey Smagin
Sweet. Easy as pumpkin pie.
rakesh
awesome web 2.0 is catching on sure and fast I too will try to develop some small web app using AJAX. And a great site too. Thanks for your effort guys
Mike Ward – yes, you can use Prototype just as easily with any server-side programming language, ASP included.