24 ways: Easy Ajax with Prototype

来源:百度文库 编辑:神马文学网 时间:2024/04/29 09:55:11
24 ways
to impress your friends
Easy Ajax with Prototype
There’s little more impressive on the web today than a appropriate touch of Ajax. Used well, Ajax brings a web interface much closer to the experience of a desktop app, and can turn a bear of an task into a pleasurable activity.
But it’s really hard, right? It involves all the nasty JavaScript that no one ever does often enough to get really good at, and the browser support is patchy, and urgh it’s just so much damn effort. Well, the good news is that – ta-da – it doesn’t have to be a headache. But man does it still look impressive. Here’s how to amaze your friends.
Introducing prototype.js
Prototype is a JavaScript framework bySam Stephenson designed to help make developing dynamic web apps a whole lot easier. In basic terms, it’s a JavaScript file which you link into your page that then enables you to do cool stuff.
There’s loads of capability built in, a portion of which covers our beloved Ajax. The whole thing is freely distributable under an MIT-style license, so it’s good to go. What a nice man that Mr Stephenson is – friends, let us raise a hearty cup of mulled wine to his good name. Cheers! sluurrrrp.
First step is todownload the latest Prototype and put it somewhere safe. I suggest underneath the Christmas tree.
Cutting to the chase
Before I go on and set up an example of how to use this, let’s just get to the crux. Here’s how Prototype enables you to make a simple Ajax call and dump the results back to the page:
var url = ‘myscript.php‘;var pars = ‘foo=bar‘;var target = ‘output-div‘;var myAjax = new Ajax.Updater(target, url, {method: ‘get‘, parameters: pars});
This snippet of JavaScript does a GET to myscript.php, with the parameter foo=bar, and when a result is returned, it places it inside the element with the ID output-div on your page.
Knocking up a basic example
So to get this show on the road, there are three files we need to set up in our site alongside prototype.js. Obviously we need a basic HTML page with prototype.js linked in. This is the page the user interacts with. Secondly, we need our own JavaScript file for the glue between the interface and the stuff Prototype is doing. Lastly, we need the page (a PHP script in my case) that the Ajax is going to make its call too.
So, to that basic HTML page for the user to interact with. Here’s one I found whilst out carol singing:
Easy Ajax

As you can see, I’ve linked in prototype.js, and also a file called ajax.js, which is where we’ll be putting our glue. (Careful where you leave your glue, kids.)
Our basic example is just going to take a name and then echo it back in the form of a seasonal greeting. There’s a form with an input field for a name, and crucially a DIV (greeting) for the result of our call. You’ll also notice that the form has a submit button – this is so that it can function as a regular form when no JavaScript is available. It’s important not to get carried away and forget the basics of accessibility.
Meanwhile, back at the server
So we need a script at the server which is going to take input from the Ajax call and return some output. This is normally where you’d hook into a database and do whatever transaction you need to before returning a result. To keep this as simple as possible, all this example here will do is take the name the user has given and add it to a greeting message. Not exactly Web 2-point-HoHoHo, but there you have it.
Here’s a quick PHP script – greeting.php – that Santa brought me early.
Season‘s Greetings, $the_name!

";?>
You’ll perhaps want to do something a little more complex within your own projects. Just sayin’.
Gluing it all together
Inside our ajax.js file, we need to hook this all together. We’re going to take advantage of some of the handy listener routines and such that Prototype also makes available. The first task is to attach a listener to set the scene once the window has loaded. He’s how we attach an onload event to the window object and get it to call a function named init():
Event.observe(window, ‘load‘, init, false);
Now we create our init() function to do our evil bidding. Its first job of the day is to hide the submit button for those with JavaScript enabled. After that, it attaches a listener to watch for the user typing in the name field.
function init(){ $(‘greeting-submit‘).style.display = ‘none‘; Event.observe(‘greeting-name‘, ‘keyup‘, greet, false);}
As you can see, this is going to make a call to a function called greet() onkeyup in the greeting-name field. That function looks like this:
function greet(){ var url = ‘greeting.php‘; var pars = ‘greeting-name=‘+escape($F(‘greeting-name‘)); var target = ‘greeting‘; var myAjax = new Ajax.Updater(target, url, {method: ‘get‘, parameters: pars});}
The key points to note here are that any user input needs to be escaped before putting into the parameters so that it’s URL-ready. The target is the ID of the element on the page (a DIV in our case) which will be the recipient of the output from the Ajax call.
That’s it
No, seriously. That’s everything.Try the example. Amaze your friends with your 1337 Ajax sk1llz.
About the author
Drew McLellan is a web developer, author and no-good swindler from just outside London, England. At theWeb Standards Project he works on press, strategy and tools. Drew keeps apersonal weblog covering web development issues and themes.
Your comments
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.
1 December 2005, 09:23
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!
1 December 2005, 09:27
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!)
1 December 2005, 11:27
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
1 December 2005, 11:32
Henrique Costa Pereira:
OH OH OH… Thats great! But I not sure about SEO technics and AJAX! Someone can tell me a trick?
1 December 2005, 12:20
Drew McLellan:
Mike Ward – yes, you can use Prototype just as easily with any server-side programming language, ASP included.
1 December 2005, 12:41
Alex Beston:
hmm – looks good!
1 December 2005, 13:25
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
1 December 2005, 13:27
MS:
Thanks
1 December 2005, 13:32
Drew McLellan:
Alex – check outgravatar.com
1 December 2005, 13:35
Philippe Jadin:
Why not simply post the content of the form to an iframe located where the div is?
No javascript…
1 December 2005, 15:15
Aaron Gustafson:
Nice one Drew. What’s next? Rudolph on Rails?
1 December 2005, 15:27
Tom Martin:
Rudolph on Rails, brilliant.
1 December 2005, 15:37
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
1 December 2005, 16:05
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"1 December 2005, 16:18
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.
1 December 2005, 16:27
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.
1 December 2005, 16:43
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 & ”!”)
@1 December 2005, 17:30
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.
1 December 2005, 18:54
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!!!
1 December 2005, 22:07
ph0tik:
Exactly, I can’t understand why you gave the code and no demo. Impress me! haha
1 December 2005, 22:27
Mart:
This is great. Its works like charm. Thanks.I cant wait till christmas now, roll ‘em on … ;)
1 December 2005, 22:34
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.
1 December 2005, 22:40
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 Itry the example it displays:
Season‘s Greetings, Stringer!
Any ideas why? Perhaps it’s my version of PHP?
1 December 2005, 23:43
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.
1 December 2005, 23:56
Haochi:
That is kinda wired.
1 December 2005, 23:57
Alistair:
Are people writing higher end frameworks utilising Prototype or is the general movement to just use Prototype and then add glue?
Al.
2 December 2005, 00:25
Prem:
I`d also like to know on how we can use the POST method with the prototype.js
does anyone know?
2 December 2005, 02:53
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?
2 December 2005, 04:52
tremendo:
Richard, suggestion for a good Ajax book:
http://www.pragmaticprogrammer.com/titles/ajax/
2 December 2005, 05:48
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
2 December 2005, 08:09
Marko Mihelcic:
I didn’t read a good article like this in a long time. Thank you.
2 December 2005, 12:53
Jens Meiert:
Very good, and it should finally clarify why Prototype is that useful!
2 December 2005, 13:00
Brian Schwartz:
Very nice. I was always a bit scared to divulge in AJAX – this is a great place to start
2 December 2005, 13:57
Paul Beardsell:
Does anybody have any Ajax and Coldfusion examples?
2 December 2005, 16:51
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 :)
2 December 2005, 17:30
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.
2 December 2005, 18:30
Steve:
Bacon, try onChange() instead.
2 December 2005, 19:48
Jim Amos:
But if I hit the back button after your demo in Safari (1.3 Panther) the browser window farts and crashes.
2 December 2005, 21:13
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/
3 December 2005, 05:34
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.
3 December 2005, 19:47
gus:
how do i send 2 different parameters to my php script with one function?
3 December 2005, 20:04
Scrambled:
How about some server-side validation done client side :)like this
Credit where its due: This is based onParticleTree’s validation script but much amended; they also havea guide to prototype
3 December 2005, 23:08
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!
5 December 2005, 01:31
devang gurjar (devdatt):
great article
5 December 2005, 08:44
Andrey Smagin:
Sweet. Easy as pumpkin pie.
5 December 2005, 15:59
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?
5 December 2005, 17:04
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.
5 December 2005, 18:24
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
6 December 2005, 02:04
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
6 December 2005, 07:06
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
6 December 2005, 20:43
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
8 December 2005, 12:29
Sopan:
Sorry, It works correct, I forgot to notics “greeting.php” script name in ajax.js file.
8 December 2005, 14:46
Pete Freitag:
Thanks for this tutorial!
8 December 2005, 16:23
jaime:
how do i begin a web page?
9 December 2005, 06:02
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
9 December 2005, 15:41
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…
9 December 2005, 17:39
Andre:
I would like to see an similar example with Coldfusion if possible…
9 December 2005, 18:25
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.
11 December 2005, 02:06
Daniele Florio:
Example of Degradable LiveSearch in AHAH
http://www.gizax.it/experiments/AHAH/degradabile/test/liveSearch.html
12 December 2005, 10:52
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!13 December 2005, 17:37
Petit:
Hi!
Terrific tutorial for a beginner to start off with!
X-tal Clear.
ThanX & Merry X-mas!
15 December 2005, 00:08
Clint Lenard:
Nice Tutorial! I learned quite a bit in such a short amount of time. :-)
18 December 2005, 01:41
Ben Scott:
think this technique would be perfect for w3c schools page suggest it to them so they can be more interactive
20 December 2005, 00:30
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
21 December 2005, 00:46
Mayuresh Kadu:
Hi,
I have just posted a link to your article on ourlocal JUG site
Nice one.
23 December 2005, 09:40
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.
24 December 2005, 17:29
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
25 December 2005, 15:46
Vital:
nice, but it not work and generate many errors in incompatible browsers, like IE5.0.. :(
26 December 2005, 14:51
commenting closed for this article
_xyz