Pete Freitag Pete Freitag

AJAX Tutorial with Prototype

Updated on November 17, 2023
By Pete Freitag
web

Here's the AJAX prototype example that I used in my AJAX presentation today.

I wanted to give an example of a good use of AJAX, and at the same time keep it simple. So I thought a good example would be to build a zip code verifier. As soon as the person enters the zip code it makes a request to the server to see if the zip code is in the database, and returns the city and state.

So the user first sees this:

zip code form input

Once the zip code is entered, and the response received it looks like this:

zip code form input with validated zip code

If the zip code is not found in the db:

zip code form input with invalid zip code

Ok, now lets build it...

Download prototype, and a zip code db

First you need to download prototype.js from prototype.conio.net (no longer works)

Next you need to downloaded a zip code database. The one I linked to is free, and for MySQL.

zipcode_example.html

<html>
<head>
<title>AJAX Zip Checker </title>
<link rel="stylesheet" href="style.css" type="text/css" />
<script src="prototype.js" language="JavaScript" type="text/javascript"></script>
<script type="text/javascript" language="JavaScript">
function checkZip() {
if($F('zip').length == 5) {
var url = 'checkZip.cfm';
var params = 'zip=' + $F('zip');
var ajax = new Ajax.Updater(
{success: 'zipResult'},
url,
{method: 'get', parameters: params, onFailure: reportError});
}
}
function reportError(request) {
$F('zipResult') = "Error";
}
</script>
</head>
<body>
<form>
<label for="zip">zip:</label>
<input type="text" name="zip" id="zip" onkeyup="checkZip();" />
<div id="zipResult"></div>
</form>
</body>
</html>

We are using the onkeyup event in the zip code input tag to fire the JavaScript function checkZip().

When the zip code length is 5, we make the AJAX request using prototype's Ajax.Updater class. This class will update the innerHTML value of any element on our page. In our example we are having it update the div with id of zipResult.

Prototype also lets us define an error handler, we are using the function reportError to handle this.

By now you're probably wondering what the $F() function does. If you aren't then you're not paying attention, or you already know! It is a function provided by AJAX to get the value of any element, for an input text box it sets the value property, on a div it sets the innerHTML property. Use it with care, it can add a perl like mystic to your JavaScript if overused.

checkZip.cfm

<cfif NOT IsDefined("url.zip") OR NOT IsNumeric(url.zip)>
<div class="badzip">Please enter a valid zip code.</div><cfabort>
</cfif>
<cfquery datasource="mysql_test" name="ziplookup">
SELECT city, state FROM zipcodes
WHERE zip = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.zip#">
</cfquery>
<cfif ziplookup.recordcount>
<div class="goodzip"><cfoutput>#ziplookup.city#, #ziplookup.state#</cfoutput></div>
<cfelse>
<div class="badzip">Zip code not found.</div>
</cfif>

Above is some ColdFusion code that outputs the city and state, or an error message.

style.css

body { font-family: verdana; }
#zipResult { position:absolute; margin-left: 20px; display:inline; color: grey; font-size:large; }
.goodzip { background: url("greencheck.gif") no-repeat left; padding-left:20px; }
.badzip { color: red; }
input { font-size: large; }
label { font-size:large; color: silver; }

Not that the CSS does much in this example, but in case your curious there it is.



ajax tutorial example javascript xml cfml css

AJAX Tutorial with Prototype was first published on December 13, 2005.

If you like reading about ajax, tutorial, example, javascript, xml, cfml, or css then you might also like:

Discuss / Follow me on Twitter ↯

Comments

Pete,

Here is a new AjaxCFC just released!
http://www.robgonda.com/blog/index.cfm

Do you think you could re-do your example with this in less code?

Sami
by Sami Hoda on 12/13/2005 at 6:18:07 PM UTC
Pete, How do you import the zip mysql database into your server? I am using mysql 5...
by Ryan Guill on 12/15/2005 at 9:59:20 AM UTC
Hey Ryan,

Easiest way would be to use the MySQL Query Browser: http://www.mysql.com/products/tools/ then file open script, and run it.
by Pete Freitag on 12/15/2005 at 10:13:49 AM UTC
Awesome! Thanks!
by Ryan Guill on 12/15/2005 at 10:22:11 AM UTC
Nice article, Another great AJAX starting article is:

http://www.johnwiseman.ca/blogging/?p=61
by John Wiseman on 01/15/2006 at 2:40:03 PM UTC
just wanted to clarify that the $F() function is not "provided by AJAX", it is part of the prototype.js library.

Also, you may want to point out that Prototype is not necessary to perform AJAX functions, it simply has some javascript functions that help make AJAX programming a bit easier.
by Ben Evans on 01/15/2006 at 2:54:49 PM UTC
Aye! A fellow central New Yorker! (I wasn't aware any existed!)

This tutorial is awesome, thanks for it, I'll definitely put it to use.

Chris
www.comitar.com
by Chris on 01/15/2006 at 8:31:11 PM UTC
Hi, I live in New Hartford, NY. I see you used the area code 13501... Do you live in Utica? :]
by Jordan Meeter on 01/15/2006 at 10:29:05 PM UTC
To expand on the comment by Kris Bright:

$F() is a function that interacts with the value of the named form element. If the 'zipResult' element was a form element, then the original code would work.

A good reference for prototype.js can be found here:
http://www.sergiopereira.com/articles/prototype.js.html
by Ben Evans on 01/16/2006 at 5:06:20 PM UTC
Just to clarify things, this tutorial was NOT stolen from "webpasties", I came up with the idea on my own, and I have never been to that site.

I don't think it is too far fetched that two people would think to use zip codes and AJAX together.
by Pete Freitag on 01/16/2006 at 9:37:24 PM UTC
Sami, thanks for mentioning ajaxCFC. Perhaps I have a similar example in my project site:

http://www.robgonda.com/blog/projects/ajaxcfc/examples/zipcode/

Cheers,

-Rob
by Rob Gonda on 01/17/2006 at 10:07:16 PM UTC
Hi Candice,

I'm not sure if the JS would run actually. An easy way to test is to just do a javascript alert... <script language="javascript" type="text/javascript">alert('hi');</script>

If that alert works then you want to do something like document.forms[0].zip.value=';

Another way to do it would be to return a status code other than 200 from your checkzip that would probably cause the reportError() function to be called. I am sure there is also probably a method in prototype that you might be able to use.
by Pete Freitag on 02/03/2006 at 9:15:49 AM UTC
this is realy a help ful tutorial
thanx
by santosh on 02/07/2006 at 4:37:32 AM UTC
I had attempted to change the success to a function, rather than having it update the contents of a div, but it never seemed to fire. (i had "success: ajaxsuccess") I then trie "success: ajaxsuccess()" which would fire the function upon success, but it did not pass along the response. I did a bit of digging around and saw on http://www.sergiopereira.com/articles/prototype.js.html that there is an Ajax.Request which just returns the response. I was then able to check the status of the response and fire off whatever events I needed.
by Critter on 02/23/2006 at 5:27:17 AM UTC
hi,

this is great!!! really nice peace of code!

does it work with old versions browsers? Where can i get a list of browsers and verstions that work with this?

I tested with:
Mozilla 1.7.12 -> OK!
Mozilla 1.6 -> OK!
IE 7 beta 2 -> OK!
IE 5 -> it do not works :( i get javascripts bugs
by marengo on 03/26/2006 at 2:47:23 AM UTC
Hi edmund,

Even i had the same problem with GET AND POST.

Found a solution;

var req;

function validate() {

if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}

function complete() {

req.onreadystatechange = processRequest;
req.open("POST", "a.php", true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send("searchmode=basic&primelocation=Colombo");
}

function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var msg = req.responseText;
alert(msg);

}
}
}

when its post you dont send the parameters in the url.

Cheers,
LDM
by Lilupa on 03/27/2006 at 12:26:05 PM UTC
hai i need full tutorial for ajax too. coz i have project using ajax in my colege! thank's ^-^ chibirima_22@yahoo.com
indonesia...
by rima on 03/28/2006 at 10:34:10 PM UTC
This code work with IE browser, but not with my Fire Fox browser. Is there a tweek to make it work with fire fox?
Again, great work; really appreciate your efforts.
by kurt on 03/29/2006 at 9:09:16 PM UTC
I would like to have more of the codes to read, otherwize its agood work.
by MUTEGANDA AMON on 04/10/2006 at 10:30:27 AM UTC
Nice work, just wondering is it good policy to create a new Ajax.Updater object on each call? (var MyAjax = new Ajax.Updater)

I can't seem to get it to work otherwise, but want to optimize if it help speed up response, lower overhead.
by allan on 04/29/2006 at 9:52:49 PM UTC
Hi guys!
Just want to share that there are some tutorials about AJAX at www.KYNOU.com.
Check it out!
by LeProgrammeur on 05/27/2006 at 3:11:58 PM UTC
Can anyone provide me the version of php + mysql for this example? Thanks...
by suthing on 06/01/2006 at 2:53:25 AM UTC
i try to use your code in dreamweaver,but it dont show proper output.Is this is proper software to make use of ajax.Plese tell me how i use your tutorial
by Aarti on 06/06/2006 at 5:23:37 AM UTC
Hi, I need full tutorial for ajax. Is it possible for u to give it as soon as possible?

Thanks,
Sachin Gupta
by Sachin Gupta on 07/13/2006 at 1:22:10 AM UTC
hey!

if you 'POST' the data to a .asp how do you fetch it with that asp?
by bcs on 07/25/2006 at 7:31:19 AM UTC
olease give me a full note on java program and some programs
by yonas on 07/28/2006 at 4:19:56 AM UTC
here's my php version...

<?php
$zipcode=$_REQUEST["zip"];
$cn=mysql_pconnect("localhost","root","mysql") or die( mysql_error());
mysql_select_db("ajax",$cn);

$sql="select * from zipcodes where zip=$zipcode";
$rs=mysql_query($sql,$cn);

if(mysql_num_rows($rs)>0){
$row=mysql_fetch_array($rs);
print "<div class='goodzip'>$zipcode is in ".$row["city"].",".$row["state"]."</div>";
}else{
print "<div class='badzip'>$zipcode Zip code not found.</div>";
}


?>
by JC on 09/28/2006 at 2:45:57 AM UTC
i was wondering how you would parse two varables for 1 sql string, like

$sql="SELECT * FROM something WHERE somethingone='$input1' AND somethingtwo='$input2'"; $rs=mysql_query($sql,$cn);
by greg on 10/18/2006 at 3:11:42 PM UTC
will u give us code for tree list creation in asp.ajax
by lijo on 12/04/2006 at 3:24:32 AM UTC
Hi,

I am building a new site in Hebrew using prototype.js
Everything works fine, but not the
new Ajax.Request('./nextPage.php', {method:'post',....
In nextPage.php I get strange character although I added
header('Content-Type: text/html; charset=WINDOWS-1255'); in the start of the PHP.

Do you know if and how I can specify the Ajax.Request to use charset=WINDOWS-1255?

Thanks and Best regards,
Eylon

The site which I am building: http://www.yaldut.com
by Eylon on 02/05/2007 at 2:03:39 AM UTC
hai i need full tutorial for ajax too. becoz i going to do the project using ajax
by siva on 06/01/2007 at 1:19:27 AM UTC
I cant get the MySQL zip code database. Would u email it to me?
by Hafiz on 07/05/2007 at 11:07:15 AM UTC
plize help me.....?
plize tell me how to stor php data without refreshing a page in ajax to database.....
by Prakash on 09/13/2007 at 3:07:40 AM UTC
Hi! Can the CheckZip.cfm be rewritten in javascript as CheckZip.js? Has someone done that already, if so, can they provide the code here?

Thanks,
Babu
by babu on 09/26/2007 at 2:20:46 PM UTC
I have a CF tag that displays a JSON string and i was wondering how could i use the above example use in the JS for the current page that is showing ?
by Rony on 10/28/2007 at 8:22:28 PM UTC
i want to change data of the one drop down corresponding to another dropdown
by MAHI on 12/08/2007 at 12:20:04 AM UTC
Dan sorry about the code formatting, my server stripped out the whitespaces.
by Pete Freitag on 06/11/2008 at 8:52:52 AM UTC
I have a prob. I have two ajax on one page. This first is to update the DB and the second on is to check the db to see if i get a return on a feld. Valed or Invaled the first ajax is working correct. The second one is not even going to the page to if it is valed or not. here is the code for the second one.

function UpdateCarrier() {
alert("UpdateCarrier");
var aryCarrierStatus = new Array();
<%
idx = 0
adoCarriers.MoveFirst
If Not adoCarriers.IsEmpty Then
Do Until adoCarriers.EOF
gstrCarrierKey = adoCarriers.Field("CO_CODE")
response.write("aryCarrierStatus[" & idx & "] = '" & gstrCarrierKey & "'; " & vbcrlf)
idx = idx + 1
adoCarriers.MoveNext
loop
end if
%>;
$A(aryCarrierStatus).each(function(S){
//Validate User ID and Password/Update DB
new Ajax.Request("ADA_CARRIER_SETUP_AJAX_0001_V100.ASP", {
method: "post",
asynchronous: true,
evalJSON: true,
parameters: {
fuse: "Getval"
,client_id: "<%=glngClientId%>"
,agent_id: "<%=gstrAgentId%>"
,user_id: "<%=glngUserID%>"
,Carrier: S
},
onSuccess: function(t) {
var json = t.responseText.evalJSON()
var strCarrierKey = json.Carrier
alert(t.responseText);
alert("Test");
if (json.Status == "V") {
$("txtStatus" + strCarrierKey).value = "Complete"
$("Status" + strCarrierKey).innerHTML = "Complete";
}
if (json.Status == "I") {
$("txtStatus" + strCarrierKey).value = "Awaiting Input"
$("Status" + strCarrierKey).innerHTML = "Awaiting Input";
}
},
onFailure: function() {
alert("failed");
strError = "failed";
}
})
})
setTimeout("UpdateCarrier()", 10000);
}
If you know a site that can help me or what I am doing wrong I would be very happy. Thank you
by Chris on 06/13/2008 at 10:10:53 AM UTC
I was wondering how I can pass the variables in this url query to a php file to ajax using prototype. All the examples I see uses form. What if the strings comes from a link...

index.php?id=12&action=default

and the php file will just echo the $_GET variables...
by Stone Deft on 06/19/2008 at 8:06:19 AM UTC
That MySQL database is now a parked domain on godaddy... Any chance that you can update this with newer code? Ill even host the database off my server if bandwidth is an issue
by Matthew on 07/22/2008 at 6:47:25 PM UTC
I´m working with Ajax and Joomla and i have a problem.

I do a sql query to the controller.php of my component. The function returns a joomla select $result=JHTML::_('select.genericlist'..., that it has a very big size (more than 10000 characters).

My problem is, if I do an echo $result, also appears the restant controller code (toolbar, body, etc.), instead only select.

The normal solution is to redirect to a new php page, and do an echo $result in that page. This allows print only the code of the select. But I can´t do this, because I can´t pass the variable in the request (it´s too big).

Someone have a solution?

Thanks
by kldojf on 10/14/2008 at 12:25:08 PM UTC