AJAX Tutorial with Prototype
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:
Once the zip code is entered, and the response received it looks like this:
If the zip code is not found in the db:
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" /> <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 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:
- Howto Build Server Side AJAX Suggestions with script.aculo.us
- AJAX Presentation Outline
- Getting Started with jQuery Mobile
- Cross Domain Data Theft using CSS
Discuss / Follow me on Twitter ↯
Tweet Follow @pfreitagComments
Easiest way would be to use the MySQL Query Browser: http://www.mysql.com/products/tools/ then file open script, and run it.
http://www.johnwiseman.ca/blogging/?p=61
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.
This tutorial is awesome, thanks for it, I'll definitely put it to use.
Chris
www.comitar.com
$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
I don't think it is too far fetched that two people would think to use zip codes and AJAX together.
http://www.robgonda.com/blog/projects/ajaxcfc/examples/zipcode/
Cheers,
-Rob
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.
thanx
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
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.> 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
indonesia...
Again, great work; really appreciate your efforts.
I can't seem to get it to work otherwise, but want to optimize if it help speed up response, lower overhead.
Just want to share that there are some tutorials about AJAX at www.KYNOU.com.
Check it out!
Thanks,
Sachin Gupta
if you 'POST' the data to a .asp how do you fetch it with that asp?
<?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>";
}
?>
$sql="SELECT * FROM something WHERE somethingone='$input1' AND somethingtwo='$input2'"; $rs=mysql_query($sql,$cn);
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
plize tell me how to stor php data without refreshing a page in ajax to database.....
Thanks,
Babu
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
index.php?id=12&action=default
and the php file will just echo the $_GET variables...
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
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