AJAX Tutorial with Prototype

Updated , First Published by Pete Freitag

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.

The Fixinator Code Security Scanner for ColdFusion & CFML is an easy to use security tool that every CF developer can use. It can also easily integrate into CI for automatic scanning on every commit.

Comments

Sami Hoda

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

Ryan Guill

Pete, How do you import the zip mysql database into your server? I am using mysql 5...

Pete Freitag

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.

Ryan Guill

Awesome! Thanks!

John Wiseman

Nice article, Another great AJAX starting article is: http://www.johnwiseman.ca/blogging/?p=61

Ben Evans

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.

Chris

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

Jordan Meeter

Hi, I live in New Hartford, NY. I see you used the area code 13501... Do you live in Utica? :]

Ben Evans

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

Pete Freitag

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.

Rob Gonda

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

Pete Freitag

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.

santosh

this is realy a help ful tutorial thanx

Critter

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.

marengo

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

Lilupa

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

rima

hai i need full tutorial for ajax too. coz i have project using ajax in my colege! thank's ^-^ chibirima_22@yahoo.com indonesia...

kurt

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.

MUTEGANDA AMON

I would like to have more of the codes to read, otherwize its agood work.

allan

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.

LeProgrammeur

Hi guys! Just want to share that there are some tutorials about AJAX at www.KYNOU.com. Check it out!

suthing

Can anyone provide me the version of php + mysql for this example? Thanks...

Aarti

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

Sachin Gupta

Hi, I need full tutorial for ajax. Is it possible for u to give it as soon as possible? Thanks, Sachin Gupta

bcs

hey! if you 'POST' the data to a .asp how do you fetch it with that asp?

yonas

olease give me a full note on java program and some programs

JC

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>"; } ?>

greg

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);

lijo

will u give us code for tree list creation in asp.ajax

Eylon

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

siva

hai i need full tutorial for ajax too. becoz i going to do the project using ajax

Hafiz

I cant get the MySQL zip code database. Would u email it to me?

Prakash

plize help me.....? plize tell me how to stor php data without refreshing a page in ajax to database.....

babu

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

Rony

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 ?

MAHI

i want to change data of the one drop down corresponding to another dropdown

Pete Freitag

Dan sorry about the code formatting, my server stripped out the whitespaces.

Chris

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

Stone Deft

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...

Matthew

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

kldojf

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