Ajax Workshop 1: Ajax basics & building a simple email verification with prototype.js.
Filed Under (Lessons, Tutorials, Workshops) by admin on 11-02-2006
This workshop will cover the basics of AJAX, what AJAX is and when it should be used.
What is AJAX?
Asynchronous JavaScript And XML, or its acronym Ajax, is a Web development technique for creating interactive web applications. The intent is to shift a great deal of interaction to the Web surfer’s computer, exchanging data with the server behind the scenes, so that the entire Web page does not have to be reloaded each time the user makes a change. This is meant to increase the Web page’s interactivity, speed, and usability. The Ajax technique uses a combination of:
- XHTML (or HTML) and CSS for marking up and styling information.
- The DOM accessed with a client-side scripting language, especially ECMAScript implementations like JavaScript and JScript, to dynamically display and interact with the information presented
- The XMLHttpRequest object to exchange data asynchronously with the web server. In some Ajax frameworks and in some situations, an IFrame object is used instead of the XMLHttpRequest object to exchange data with the web server.
- XML is commonly used as the format for transferring data, although any format will work, including preformatted HTML, plain text, JSON and even EBML.
Like DHTML, LAMP, or SPA, Ajax is not a technology in itself, but a term that refers to the use of a group of technologies together. In fact, derivative/composite technologies based substantially upon Ajax, such as AFLAX, are already appearing.
http://en.wikipedia.org/wiki/AJAX
When should AJAX be used?
- Form driven interaction
- Deep hierarchical tree navigation
- Rapid user-to-user communication
- Voting, Yes/No boxes, Ratings submissions
- Filtering and involved data manipulation
- Commonly entered text hints/auto completion
When shouldn’t AJAX be used?
- Simple forms
- Search
- Basic navigation
- Replacing a large amount of text
- Display manipulation
- Useless widgets
http://weblog.patrice.ch/web/places-where-ajax-should-be-used.html
Introduction to AJAX
In this introduction we will build a simple form (I know it says not to use AJAX for simple forms, but it is an easy example) that submits a user’s information to the database and confirms if the user’s email address is already in the database. We will be using a common JavaScript library by the name of prototype.js which can be downloaded at http://prototype.conio.net/.
Lesson1.html
To start off we will need a simple XHTML form that will ask the user for their first name, last name and email address. Make sure every field has descriptive id and name attributes. We also need a button to attach an event to (events are user’s actions on the page i.e. mouse over, mouse out, click etc…)
Example:
<input name="fname" type="text" id="fname" /><br /> <input name="lname" type="text" id="lname" /><br /> <input name="email" type="text" id="email" /><br /> <input type="button" id="submit" value="Submit" />
The next thing we need to do is add the JavaScript that will add the event to the button. We will be using a code shortcut from the prototype.js library that replaces document.getElementByID() with $().
Example:
function init () { $('submit').onclick = function () { sendData(); } }
We created a function called init() that is short for initiate that will be called once the body has loaded. The next thing we did was get the element with the ID of submit (the button we made earlier) and attach an on click event to it. This could have also been done inline but when there is a lot of code and debugging starts it’s easier to manage when you dynamically add the event. The function sendData() we added will be used to send the information from the form to the PHP page first to check if the email address exists and if it’s a new address add the information to the database. Here is what the sendData() function looks like.
function sendData () { var url = 'process.php'; var pars = Form.serialize('frm'); var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); }
The first variable URL is used tell the AJAX object what page we want to send the information too, the second variable pars short for parameters is used to tell the AJAX object which values are to be passed to the URL. You can think of this as the query string in the browser. The Form.serialize() function is from the prototype.js library and is used to get all the values from the form and serialize them in a way that the AJAX object can send. It is the same format as the GET method of a standard form:
i.e. fname=steve&lname=brown&email=steve@hotmail.com
The next variable myAjax is initializing the AJAX object and passing all the needed information to it. As you can see you can set the method and set what functions are needed during the AJAX process.
onLoading: This is when the AJAX object is communicating with the server, for this you can show an indicator that tells the user that the data is being sent to the server.
onComplete: This is when the AJAX object has completed communicating with the server, you can now display the information you received from the server to the user.
We also attach functions to these events: showLoad and onComplete accordingly.
function showLoad () { $('load').style.display = 'block'; } function showResponse (originalRequest) { var newData = originalRequest.responseText; $('load').style.display = 'none'; $('status').innerHTML = newData; }
We also need to add two new divs to the page:
<div id="load" style="display:none">loading...</div> <div id="status"></div>
The function showLoad changes the style display of the div with the ID load to block from none. The function showResponse gets the data back from process.php and displays the information in the div with the ID of status as well as sets the style display of load from block to none.
Process.php
<?php function stringForJavascript($in_string) { $str = ereg_replace("[\r\n]", " \\n\\\n", $in_string); $str = ereg_replace('"', '\\"', $str); Return $str; } $fname = $_GET['fname']; $lname = $_GET['lname']; $email = $_GET['email']; // CHECK THE DATABASE TO SEE IF EMAIL EXISTS // THIS IS JUST A PLACE HOLDER $_email = "steve@hotmail.com"; if ($_email == $email) { // SEND ERROR BACK print stringForJavascript("ERROR"); usleep(400000); } else { // ADD INFORMATION TO DATABASE // THIS IS JUST A PLACE HOLDER // SEND SUCCESS BACK print stringForJavascript("SUCCESS"); usleep(400000); } ?>
This page is straight forward; there is a function at the top stringForJavascript that will format the code correctly for JavaScript. Next you would check the database to see if the email exists, here we only have one email address and we will check against that. If it matches we send back in plain text that there was an error and if there was no match a success.
As you see this was a simple example and there is a lot more that can be done. In future lessons we will discuss sending back multiple variables to be parsed back into the HTML as well as creating elements on the fly with DOM.
Lesson1.html Complete Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Ajax Lesson</title> <script src="prototype.js" type="text/javascript"></script> <script type="text/javascript"> function init () { $('submit').onclick = function () { sendData(); } } function sendData () { var url = 'process.php'; var pars = Form.serialize('frm'); var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, onLoading: showLoad, onComplete: showResponse} ); } function showLoad () { $('load').style.display = 'block'; } function showResponse (originalRequest) { var newData = originalRequest.responseText; $('load').style.display = 'none'; $('status').innerHTML = newData; } </script> </head> <body onload="init()"> <div id="load" style="display:none">loading...</div> <div id="status"></div> <form name="frm" id="frm" > <input name="fname" type="text" id="fname" /> <input name="lname" type="text" id="lname" /> <input name="email" type="text" id="email" /> <input type="button" id="submit" value="Submit" /> </form> </body> </html>










A very helpful tutorial. Good job!
Thank you, I appreciate the kind words
Its goot to finally see a how to article using prototype.js
Your code examples are inside two nested sets of scroll bars… makes it very annoying to try and read.
Thanks, about the code examples; they are fine in Mozilla based browsers and Opera but mess up in IE, I will look into fixing them.
Great job and happy to found a so welcome ressources portal
A wonderful site : full (RSS, workshop, lessons, tutorials, samples), readable, excellent design…
Continue…
PRAISE JEEBUS!!!!!!
I finally got something to work. now WTF to I do with it….
Hi, I noticed that in IE it just stays on the loading… status. I am sure that it can load the content just fine, as it works in FF, but IE is just not showing the loaded content or something. Please let me know if you have any idea how to fix it. I guess for now I have to use some browser detection so that IE users aren’t getting a loading screen at all.
Wonderful and Simple sweet article
keep it up !!
Very simple and to the point.
I’m wondering however if this can be used with ASP instead of PHP.
thanks. Don’t stop now!
Thank you very much!
thanks, really a wonderful & helpful tutorial, Thanks a lot for ur A wonderful site
thank u once again !
lovely set of workshop tutorials but noticed in workshop 1 that the form does not validate (lacks an action attribute).
if you add action=”#” to the tag then the form will validate okay.
How do i implement this with servlet?
Really rockz tutorial.. Thanx.. Go on cool work m8..
Thank you this was really helpful. I was able to implement this with ASP very quickly.
it’s not AJAX. you don’t process any XML. it’s AJAT. T == text.
anyway thanks for the demonstration of prototype. :p I like it
Interesting. Very helpful tutorial.
Do u have ajax code samples for using XSL instead of PHP.
I am developing a gaming website using ajax & XSLT and require some useful sites (probably ajax links tutorials for form validation , site functionality).
Anyone here knows about any gaming websites developed using ajax.
Thanks,
Prashant
An excellent tutorial…very helpful..Thanx..and all the best for the best ones to come in future..
Great tutorial! Very simple and straightforward.
My head is spinning as I try to wrap my brain around all the new leaps forward… is this AFLAX thing the same as FLEX?
I just interviewed two guys who have developed what they call FJAX as a way to use Flash to get past some of the uglier sides of AJAX.
How can you justify not using AJAX for “simple forms” or “search”? Surely AJAX is used for improved website interaction.
Hi
After copying your code it seems to call the onLoad + showResponse in the wrong order, if i put alerts in these functions it calls showresponse 1st.
Any ideas ???
I use firefox but when testing in IE this doesn’t work… any ideas?
A Good TUtorial, how ever make it convinient to read the content with in the scroll bar
Thank you very much!
Thank you very much!
An excellent resource! But you need to eliminate the double scroll bars…
Other than that - will continue to check the site periodically. Good examples of “ajax imaging” are always points of interest….
Good Job, really very helpful tutorial
Excellent beginner’s article…
Well Done !!!!
very helpful tutorial.Thanks to writer.