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>
Technorati Tags: technorati , technorati , technorati
Share and Enjoy:
  • Digg
  • del.icio.us
  • Technorati
  • Google
  • Reddit
  • Slashdot
  • StumbleUpon
  • YahooMyWeb

Comments:

28 Comments posted for Ajax Workshop 1: Ajax basics & building a simple email verification with prototype.js.

Make a comment