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.
Tweet
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
- Cross Domain Data Theft using CSS - July 21, 2010
- jQuery UI Sortable Tutorial - January 7, 2010
- Ajax Same Origin Policy No More with Firefox 3.5 - June 30, 2009
Trackbacks
Trackback Address: 515/921252C4E2791202EAACAEF9DE1E90CA
- 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
Comments
On 12/13/2005 at 8:18:07 PM EST Sami Hoda wrote:
1
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
On 12/15/2005 at 11:59:20 AM EST Ryan Guill wrote:
2
Pete, How do you import the zip mysql database into your server? I am using mysql 5...
On 12/15/2005 at 12:13:49 PM EST Pete Freitag wrote:
3
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.
On 12/15/2005 at 12:22:11 PM EST Ryan Guill wrote:
4
Awesome! Thanks!
On 01/15/2006 at 4:40:03 PM EST John Wiseman wrote:
5
Nice article, Another great AJAX starting article is:
http://www.johnwiseman.ca/blogging/?p=61
On 01/15/2006 at 4:54:49 PM EST Ben Evans wrote:
6
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.
On 01/15/2006 at 5:20:45 PM EST Anonymous wrote:
7
Uholy macarena! I just found out much do my eyes hurt by doing things in bare javascript and html. You should have a look at seaside.
On 01/15/2006 at 5:44:09 PM EST Anonymous wrote:
8
Nice. Stolen from http://www.webpasties.com/xmlHttpRequest/ though.
On 01/15/2006 at 9:45:01 PM EST Some guy wrote:
9
Please please please learn the difference between "your" and "you're". It takes away from your otherwise excellent tutorial.
On 01/15/2006 at 10:31:11 PM EST Chris wrote:
10
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
On 01/16/2006 at 12:29:05 AM EST Jordan Meeter wrote:
11
Hi, I live in New Hartford, NY. I see you used the area code 13501... Do you live in Utica? :]
On 01/16/2006 at 5:46:33 AM EST Mick OReilly wrote:
12
While this is only an example, it's important for developers to ensure that their form will still validate without a zip code as there are billions of people outside the US who do not use zip codes.
On 01/16/2006 at 7:50:02 AM EST Anonymous wrote:
13
Anonymous said: "Uholy macarena! I just found out much do my eyes hurt by doing things in bare javascript and html. You should have a look at seaside."
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. :)
On 01/16/2006 at 10:17:10 AM EST Dave wrote:
14
A working example would have been nice, so we could see the AJAX in action.
On 01/16/2006 at 6:57:01 PM EST Kris Bright wrote:
15
I believe your error handling section needs to be changed ...
from: $F('zipResult') = "Error";
to: $('zipResult').innerHTML = "Error";
I enjoyed the tutorial.
Thanks, Kris
On 01/16/2006 at 7:06:20 PM EST Ben Evans wrote:
16
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
On 01/16/2006 at 11:37:24 PM EST Pete Freitag wrote:
17
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.
On 01/18/2006 at 12:07:16 AM EST Rob Gonda wrote:
18
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
On 01/18/2006 at 6:05:02 AM EST qwerty wrote:
19
i want ajax examples
On 02/03/2006 at 10:24:17 AM EST Candice wrote:
20
Thanks for the example. I used it to create a validator for application fee waiver codes on a college website. It works pretty much exactly the same way that this example works. My only question is, is there a way to clear the input box when the code is invalid? I tried adding javascript to my 'checkwaiver.cfm' file (which would be the equivalent of 'checkzip.cfm') but the javascript does not run at all. Thanks!
On 02/03/2006 at 11:15:49 AM EST Pete Freitag wrote:
21
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.
On 02/03/2006 at 12:09:15 PM EST Candice wrote:
22
Thanks for the response Pete. No javascript in checkwaiver.cfm will run - not even a simple alert. I will look through prototype for a method that does what I'm looking for.
On 02/07/2006 at 6:37:32 AM EST santosh wrote:
23
this is realy a help ful tutorial thanx
On 02/09/2006 at 12:06:03 PM EST dennis wrote:
24
Squeak doesn't have such an awful learning curve, I know a high-school kid who's doing just fine with it. A good tutorial on Seaside is at http://beta4.com/seaside2/tutorial.html...takes less than an hour to go through, and it's quite impressive.
On 02/23/2006 at 7:27:17 AM EST Critter wrote:
25
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.
On 02/28/2006 at 8:28:30 PM EST jais wrote:
26
Hi
Can I Use Ajax for live streaming of data from stock market for trading.
Regards jais
On 03/11/2006 at 2:04:23 AM EST alex wrote:
27
jais, to use AJAX for live streaming of stock quotes check out the "streaming AJAX" paradigm implemented by Lightstreamer. See www.lightstreamer.com (many online demos are available).
On 03/21/2006 at 11:32:30 AM EST edmund wrote:
28
Hi,
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
On 03/26/2006 at 4:47:23 AM EST marengo wrote:
29
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
On 03/27/2006 at 2:26:05 PM EST Lilupa wrote:
30
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
On 03/28/2006 at 4:13:31 AM EST preet wrote:
31
hi, i need full tutorial for ajax.is it possible for u to give
On 03/29/2006 at 12:34:10 AM EST rima wrote:
32
hai i need full tutorial for ajax too. coz i have project using ajax in my colege! thank's ^-^ chibirima_22@yahoo.com indonesia...
On 03/29/2006 at 11:09:16 PM EST kurt wrote:
33
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.
On 04/10/2006 at 12:30:27 PM EDT MUTEGANDA AMON wrote:
34
I would like to have more of the codes to read, otherwize its agood work.
On 04/29/2006 at 11:52:49 PM EDT allan wrote:
35
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.
On 05/05/2006 at 1:11:43 PM EDT PHP Coder wrote:
36
Hi,
I tried to rewrite this in PHP (version 4) but I get a javascript error "Object Expected"
Any thoughts?
On 05/05/2006 at 1:43:57 PM EDT PHP Coder wrote:
37
Nevermind - stupid mistake... Thanks for the tutorial, I rewrote it in PHP and works brilliantly!
On 05/10/2006 at 7:16:03 AM EDT Jessey wrote:
38
This tutorial has been a big help. However, I haven't been able to use a full url (our coldfusion server is on a separate box). I had to place all the files on the cf server. Any reason why this would be?
On 05/10/2006 at 2:29:38 PM EDT Jessey wrote:
39
AH, I figured it out. The whole cross-domain security thing, thus I need a proxy.
On 05/14/2006 at 10:43:41 PM EDT Cj wrote:
40
Thanks for the tutorial - I also re-wrote it in PHP + MySQL and it worked a treat.
Cj
On 05/14/2006 at 11:10:23 PM EDT Free Articles Tutorials wrote:
41
A working example would have been nice, so we could see the AJAX in action.
On 05/14/2006 at 11:11:09 PM EDT Free Articles Tutorials wrote:
42
A working example would have been nice, so we could see the AJAX in action.
http://www.excellentguide.com/article
On 05/14/2006 at 11:11:40 PM EDT Free Articles Tutorials wrote:
43
AH, I figured it out. The whole cross-domain security thing, thus I need a proxy.
http://www.excellentguide.com/article
On 05/18/2006 at 5:40:25 PM EDT Bharat wrote:
44
$F is function provided by prototype, not AJAX
On 05/27/2006 at 5:11:58 PM EDT LeProgrammeur wrote:
45
Hi guys! Just want to share that there are some tutorials about AJAX at www.KYNOU.com. Check it out!
On 06/01/2006 at 4:53:25 AM EDT suthing wrote:
46
Can anyone provide me the version of php + mysql for this example? Thanks...
On 06/02/2006 at 12:15:21 PM EDT Sebastien wrote:
47
Hi! Thanks for sharing! I tried to do so successfully on my web site but I have a problem with variables.
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.
On 06/06/2006 at 7:23:37 AM EDT Aarti wrote:
48
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
On 06/07/2006 at 1:46:26 PM EDT Jerry Hughes wrote:
49
How do you make the result of the Ajaz response into a session variable? I returned a drop down box, seleclted one of the items from the drop down box, but cant figure how to make the selection a session variable.
On 06/08/2006 at 5:09:33 AM EDT Sebastien wrote:
50
@Jerry: I just did like I used for it: declare your session (session_start()) and after set your session variable with the GET value.
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!
On 07/05/2006 at 7:46:33 AM EDT Micheal wrote:
51
Good Tutorial. i will try this tutorial to www.flashgameworld.net
On 07/10/2006 at 9:01:22 AM EDT Nice guy wrote:
52
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. :)
----- 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.
On 07/13/2006 at 3:22:10 AM EDT Sachin Gupta wrote:
53
Hi, I need full tutorial for ajax. Is it possible for u to give it as soon as possible?
Thanks, Sachin Gupta
On 07/24/2006 at 2:37:15 PM EDT Luke Rohenaz wrote:
54
redid the CFM file in PHP, hope is pastes ok:
<?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>"; } ?>
On 07/25/2006 at 9:31:19 AM EDT bcs wrote:
55
hey!
if you 'POST' the data to a .asp how do you fetch it with that asp?
On 07/28/2006 at 6:19:56 AM EDT yonas wrote:
56
olease give me a full note on java program and some programs
On 07/31/2006 at 12:16:34 AM EDT Drew wrote:
57
can anyone share a php version of this? thanks. -drew;)
On 09/22/2006 at 10:59:27 AM EDT hebiryu wrote:
58
@yonas..
hahaha... you can try on PHP 5 or 4.
On 09/28/2006 at 4:45:57 AM EDT JC wrote:
59
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>"; }
?>
On 10/09/2006 at 8:24:26 PM EDT http://www.news-technology.net wrote:
60
Thanks for the tutorial
On 10/12/2006 at 9:01:00 AM EDT Neo wrote:
61
this is my version in PHP, hope this helps. Visit my site for more AJAX Tutorial www.technorepublic.com
<?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>"; ?>
On 10/18/2006 at 5:11:42 PM EDT greg wrote:
62
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);
On 10/27/2006 at 11:15:07 AM EDT mark wrote:
63
I would also like to know how to get this to work for firefox. Thanks !
On 11/22/2006 at 1:21:28 AM EST santosh wrote:
64
Nice no words to say
On 11/25/2006 at 1:53:29 AM EST Rama krishna wrote:
65
How to use DIV tag in AJAX
On 12/04/2006 at 5:24:32 AM EST lijo wrote:
66
will u give us code for tree list creation in asp.ajax
On 12/09/2006 at 6:05:52 PM EST www.elektrotekno.com wrote:
67
does ajax has extremely CPU usage? tjere are same mods for phpbb systems, so I reluctant use it
On 12/11/2006 at 4:16:37 PM EST Alaa Moustafa wrote:
68
Ajaxlines will help you to find all resources to learn and know all about Ajax technology, by providing you with the latest Ajax Tutorials, Ajax Toolkits, Ajax Articles and Ajax Services.
http://www.ajaxlines.com
On 12/22/2006 at 4:59:35 AM EST zee wrote:
69
I am facing javascript error. Please check the following code.
<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>
On 01/02/2007 at 1:10:08 PM EST DEViNE wrote:
70
Zee, one thing that looks suspicious is $F('display_here') = originalRequest.responseText;
Try changing it to $F('display_here').innerHTML = originalRequest.responseText;
On 01/09/2007 at 11:55:28 AM EST Paul wrote:
71
Ive been looking around and came across this ajax and im not sure if it can be done. I hope somone can help me out. Heres what i need.
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.
On 02/05/2007 at 3:46:20 AM EST eylon wrote:
72
Hi, I have a problem with Ajax.Updater, Instead of hebrew characters CHARSET=WINDOWS-1255 it send me other characters, any ideas?
http://www.eshmore.com
On 02/05/2007 at 4:03:39 AM EST Eylon wrote:
73
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
On 06/01/2007 at 3:19:27 AM EDT siva wrote:
74
hai i need full tutorial for ajax too. becoz i going to do the project using ajax
On 06/01/2007 at 3:20:48 AM EDT sivanantham wrote:
75
hai i need full tutorial for ajax too. coz i have project using ajax, dharma_siva@yahoo.co.in
On 07/05/2007 at 1:07:15 PM EDT Hafiz wrote:
76
I cant get the MySQL zip code database. Would u email it to me?
On 07/08/2007 at 12:03:40 PM EDT Anonymous wrote:
77
Hi Pete, This article is very good. It would be nice if you can send me the complete presentation. Also, i cant get MySQL zip code database.
Thanks.
On 08/08/2007 at 5:31:38 PM EDT AltaGid wrote:
78
Hello! Help solve the problem. Very often try to enter the forum, but says that the password is not correct. Regrettably use of remembering. Give like to be? Thank you!
On 08/20/2007 at 4:25:18 AM EDT verroest wrote:
79
great example, but in Safari 3.0.3 it doesn't work without the .innerHTML:
function reportError(request) { $F('zipResult').innerHTML = "Error"; }
Thanks!
On 09/13/2007 at 5:07:40 AM EDT Prakash wrote:
80
plize help me.....? plize tell me how to stor php data without refreshing a page in ajax to database.....
On 09/26/2007 at 4:20:46 PM EDT babu wrote:
81
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
On 10/28/2007 at 10:22:28 PM EDT Rony wrote:
82
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 ?
On 12/03/2007 at 8:48:57 PM EST Sean Beam wrote:
83
Nice article! Next time do not copy from other site! Plz do your own!
On 12/08/2007 at 2:20:04 AM EST MAHI wrote:
84
i want to change data of the one drop down corresponding to another dropdown
On 05/08/2008 at 4:18:53 PM EDT coderbari wrote:
85
Great example man.It will help me a lot.I am developing my site and want to use some AJAX based thing in it.I will prototype for it.You this article will help me a lot. Thanks.
Bari http://www.coderbari.com
On 06/11/2008 at 10:45:05 AM EDT dan wrote:
86
formate your code dude..
On 06/11/2008 at 10:52:52 AM EDT Pete Freitag wrote:
87
Dan sorry about the code formatting, my server stripped out the whitespaces.
On 06/13/2008 at 12:10:53 PM EDT Chris wrote:
88
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
On 06/19/2008 at 10:06:19 AM EDT Stone Deft wrote:
89
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...
On 07/07/2008 at 9:24:06 AM EDT think wrote:
90
who are u..
On 07/22/2008 at 8:47:25 PM EDT Matthew wrote:
91
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
On 10/14/2008 at 2:25:08 PM EDT kldojf wrote:
92
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
On 03/27/2009 at 11:41:12 PM EDT OutThisLife wrote:
93
Hmm! This looks great. It's a bit outdated though, no? I'll give it a try if I can find another Zip Code database :)
On 04/19/2009 at 8:16:48 AM EDT tsogoo wrote:
94
thank to simple and understandable tutorial
On 06/08/2009 at 7:40:12 AM EDT Sajid wrote:
95
simple and understandable tutorial.. http://www.allergycheckpoint.com Thanks
On 01/07/2010 at 1:52:08 PM EST igorlinkov wrote:
96
I want to quote your post in my blog. It can? And you et an account on Twitter?
On 08/03/2010 at 7:21:20 AM EDT Theorohybeamb wrote:
97
Hey What's up guys
First time posting
Post a Comment
Recent Entries
- Howto Install and Run the Android Emulator
- jQuery UI Autocomple IE 6 Select List z-Index Issues
- Path Traversal Vulnerability Security Hotfix for ColdFusion Released
- Using AntiSamy with ColdFusion
- Writing Secure CFML Slides from CFUnited 2010
- Locking Down ColdFusion Presentation Slides
- Cross Domain Data Theft using CSS
- Using jQuery UI Autocomplete with Hidden ID's
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
First time posting







