pf » AJAX Tutorial with Prototype
AJAX Tutorial with Prototype
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
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.
add to del.icio.us
| Tags: ajax, tutorial, example, javascript, xml, cfml, css
Related Entries
- Howto Build Server Side AJAX Suggestions with script.aculo.us - December 6, 2006
- AJAX Presentation Outline - December 13, 2005
- Adobe AIR Tutorial for HTML / JavaScript Developers - February 25, 2008
- Ext CFC - December 12, 2007
- Application.cfm and AJAX - February 5, 2007
- The Ajax buzz Christoph Schmitz
- Ajax (or Flash) Startpages (or Homepages) 3spots ? ? ?
- Cold Fusion + Prototype Ajax presentation and example code Ajaxian
- Ajax with Prototype Baz Web Development: Ajax, FastCGI, Joomla
- Ajax and Libraries Enterprise Abstraction
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
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
As the seaside site says: "Seaside is a framework for developing sophisticated web applications in Smalltalk." There are other much better web application frameworks in languages with a smaller learning curve and much more usage on the net (reusable skills) that do the same encapsulation as seaside.
Or you could just learn some javascript and html. :)
from: $F('zipResult') = "Error";
to: $('zipResult').innerHTML = "Error";
I enjoyed the tutorial.
Thanks, Kris
$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.
Can I Use Ajax for live streaming of data from stock market for trading.
Regards jais
After reading your site with the ajax tutorial, I was trying to change the GET method to a POST method.
I am not sure why the following doesn't work, I apprecipate your insight to solving this problem
// the ajax script var url = "process.php"; http.open("POST", url, true); ... // then in the html form, i use method="post" and have a input field with 'username' as id and name.
in the process.php <? $username = $_POST['username']; ?>
But whenever I use the POST in the ajax script, I can't get anything in the username
I can only do it with a GET (as in your example in the webpage)
// the ajax script var username = ...; var url = "process.php?param="; http.open("POST", url + username, true);
I will apprecipate if you can tell me what's wrong with the POST
Thank you Edmund
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.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
I can't seem to get it to work otherwise, but want to optimize if it help speed up response, lower overhead.
I tried to rewrite this in PHP (version 4) but I get a javascript error "Object Expected"
Any thoughts?
Cj
http://www.excellentguide.com/article
http://www.excellentguide.com/article
In fact, I try to set session variables with my external page ($_SESSION['offset']=$_GET['offset'];), this page does receive GET informations since echo $_SESSION['offset'] works but this seems to keep local since no change appear on my first page. Thanks for helping.
In details:
For your main page in the Javascript: var yourvalue1= document.getElementById("yourdiv").yourvalue1.value; var yourvalue2= document.getElementById("yourdiv").yourvalue2.value; var params = 'yourvalue1=' + yourvalue1 + '&yourvalue2=' + yourvalue2 (and more if you want); var url = 'ajax-response.php'; (...)
For "ajax-response.php": <? session_start(); $_SESSION['yourvalue1']=$_GET['yourvalue1']; $_SESSION['yourvalue2']=$_GET['yourvalue2']; ?>
My problem remains: the main page doesn't see the new values without refreshing it! If someone could help, I'd be very pleased!
Or you could just learn some javascript and html. :)
----- You're totally wrong here. Smalltalk has the shortest learning curve possible. Check out the BNF and semantics with two or three smalltalks (Squeak, VisualWorks, Dolphin) before writing.
Thanks, Sachin Gupta
<?php $link = mysql_connect('localhost', 'db_username', 'db_pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('your_db_name', $link); if (!$db_selected) { die ('Can not use this db: ' . mysql_error()); }
$sql = "SELECT * FROM zipcodes WHERE zip = '$_REQUEST[zip]'"; $result=mysql_query($sql); $num = mysql_num_rows($result); if($num > 0) { while($thiszip=mysql_fetch_array($result)) { echo "<span class=\"goodzip\">$thiszip[city], $thiszip[state]</span>"; } } else { echo "<span class=\"badzip\">Zip Code Not Found</span>"; } ?>
if you 'POST' the data to a .asp how do you fetch it with that asp?
hahaha... you can try on PHP 5 or 4.
<?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>"; }
?>
<?php function connectdb() { $mysqluser="USER"; $mysqlpasswd="PASS"; $mysqlhost="LOCALHOST"; $dbname="DBNAME";
$connID = mysql_connect($mysqlhost, $mysqluser, $mysqlpasswd); if ($connID) { mysql_select_db($dbname); return $connID; } else exit(); }
if($zip!="" && is_numeric($zip)) { $connID=connectdb(); $q=mysql_query("SELECT city, state FROM zipcodes WHERE zip=$zip"); $r=mysql_fetch_array($q); if($r) { echo "<div class=\"goodzip\">$r[0], $r[1]</div>"; } else echo "<div class=\"badzip\">Zip code not found.</div>"; mysql_close($connID); } else echo "<div class=\"badzip\">Please enter a valid zip code.</div>"; ?>
$sql="SELECT * FROM something WHERE somethingone='$input1' AND somethingtwo='$input2'"; $rs=mysql_query($sql,$cn);
http://www.ajaxlines.com
<script src="dist/prototype.js" language="javascript" type="text/javascript"></script> <script language="javascript"> // JavaScript Document function ajaxFunction(industry_id) { var user_id = $F('user_id'); var url = 'js_select_industry.php'; var pars = 'user_id=' + user_id + '&industry_id=' + industry_id; var ajax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: showResponse }); } function showResponse(originalRequest) { $F('display_here') = originalRequest.responseText; } </script>
Try changing it to $F('display_here').innerHTML = originalRequest.responseText;
a page with textbox and an iframe.
the iframe defaults to a basic index holding page.
the user enters his mailbox name eg fred
this then opens the following url http://10.0.0.3/exchange/ and adds the variable onto the end
http://10.0.0.3/exchange/fred
please note the site is running off the following url http://10.0.0.2 so its a completely different url.
Is it even possible to change the parent url of the iframe. I hope you guys can help you sound brainy enough.
http://www.eshmore.com
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
Thanks.
function reportError(request) { $F('zipResult').innerHTML = "Error"; }
Thanks!
Thanks, Babu
Bari http://www.coderbari.com
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
- Top 10 Reserved SQL Keywords
- Web Design Tips for Programmers
- Geolocation API for Adobe AIR?
- Dear SQL Server Enterprise Manager Developer
- PostalMethods - Web Service for Snail Mail
- Mastering CFQUERYPARAM
- Google Code Search for ColdFusion
- Speaking at CFUNITED 2008
RSS
Pete Freitag is a software engineer, and web developer located in










