Showing posts with label onreadystatechange. Show all posts
Showing posts with label onreadystatechange. Show all posts

AJAX Form Validation - Learn step by step

AJAX Form Validation learn step by step

1. Connect to the ajax database, and create a table named users with the following code:

CREATE TABLE users

(

user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,

user_name VARCHAR(32) NOT NULL,

PRIMARY KEY (user_id)

);

2. Execute the following INSERT commands to populate your users table with some sample data (because user_id is an auto_increment column, its values will be generated by the database):

INSERT INTO users (user_name) VALUES ('bogdan');

INSERT INTO users (user_name) VALUES ('filip');

INSERT INTO users (user_name) VALUES ('mihai');

INSERT INTO users (user_name) VALUES ('emilian');

INSERT INTO users (user_name) VALUES ('paula');

INSERT INTO users (user_name) VALUES ('cristian');

3. In your ajax folder, create a new folder named validate.

4. Let's start writing the code with the presentation tier. Create a file named validate.css, and add the following code to it:

body

{
font-family: Arial, Helvetica, sans-serif;
font-size: 0.8em;
color: #000000;
}

label
{
float: left;
width: 150px;
font-weight: bold;
}
input, select
{
margin-bottom: 3px;
}
.button
{
font-size: 2em;
}
.left
{
margin-left: 150px;
}
.txtFormLegend
{
color: #777777;
font-weight: bold;
font-size: large;
}
.txtSmall
{
color: #999999;
font-size: smaller;
}
.hidden
{
display: none;
}
.error
{
display: block;
margin-left: 150px;
color: #ff0000;
}


AJAX Form Validation
AJAX Form Validation - Learn step by step PART-2

AJAX Form Validation - Learn step by step PART-3
AJAX Form Validation - Learn step by step PART-4
AJAX Form Validation - Learn step by step PART-5
AJAX Form Validation - Learn step by step PART-6


XML in ACTION : AJAX Sample Program

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en"> <head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<title>Ajax learners</title>
<script type="text/javascript" src="fetchxml.js"></script>
</head>
<body>
<h1>Ajax Technologies</h1>
<ul>
<li>
<a href="w3c.xml"
onclick="grabFile(this.href); return false;">W3C</a>
</li>
<li>
<a href="XML.xml"
onclick="grabFile(this.href); return false;">XML</a>
</li>
<li>
<a href="CSS.xml"
onclick="grabFile(this.href); return false;">CSS</a>
</li>
<li>
<a href="XMLHttpRequest.xml"
onclick="grabFile(this.href); return false;">XMLHttpRequest</a>
</li>
<li>
<a href="JavaScript.xml"
onclick="grabFile(this.href); return false;">JavaScript</a>
</li>
</ul>
<div id="details"></div>
</body>
</html>


// JavaScript Document fetchxml.js
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
}

function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
parseResponse(request);
};
request.open("GET", file, true);
request.send(null);
}
}

function parseResponse(request) {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
var data = request.responseXML;
var name = data.getElementsByTagName("name")[0].
firstChild.nodeValue;
var website = data.getElementsByTagName("website")[0].
firstChild.nodeValue;
var email = data.getElementsByTagName("email")[0].
firstChild.nodeValue;
var header = document.createElement("h2");
var mailto = document.createElement("a");
mailto.setAttribute("href","mailto:"+email);
var text = document.createTextNode(name);
mailto.appendChild(text);
header.appendChild(mailto);
var link = document.createElement("a");
link.setAttribute("href",website);
var linktext = document.createTextNode(website);
link.appendChild(linktext);
var details = document.getElementById("details");

while (details.hasChildNodes()) {
details.removeChild(details.lastChild);
}

details.appendChild(header);
details.appendChild(link);
}
}
}

AJAX at work - Sample program demonstrating AJAX

//Select this following code, paste in dreamweaver or any text editor.
// save them in any web server root directory. I saved in wwwroot of
// Inetpub. execute the program using "http" protocol for instance //"http://localhost/ajaxprograms/Index.html" .

//Index.html


<html>

<head>
<title> Ajax at work <⁄title>

<script language = "javascript">
var XMLHttpRequestObject = false;

if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);

XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}

XMLHttpRequestObject.send(null);
}
}
<⁄script>
<⁄head>

<body>

<h1> Fetching data with Ajax <⁄h1>

<form<
<input type = "button" value = "Display Message"
onclick = "getData('data.txt', 'targetDiv')">
<⁄form>

<div id="targetDiv">
<p>The fetched data will go here.<⁄p>
<⁄div>

<⁄body>
<⁄html>

//data.txt
This text was fetched using Ajax.

Let us revise some key points about AJAX step by step:

The XMLHttpRequest object is the heart and soul of Ajax. Its methods and properties drive the asynchronous requests that make Ajax applications feel so responsive.

In this sample AJAX program, we’ve seen how to use the XMLHttpRequest object in three steps:

1. Create an instance of the object that will work across different browser implementations.
2. Prepare a request using the onreadystatechange event handler, the open method, and the send method.
3. Process the response from the server through the properties readyState, status, responseText, and sometimes responseXML.

This basic model will remain unchanged for all the AJAX programs.


XMLHttpRequest Object readyState property

Now we've been introduced to XMLHttpRequest object, their are two properties you should get to know this object and object supports. first is the readyState property of XMLHttpRequest object. the ready state property tells you what's going on XMLHttpRequest object as it is downloading data .
we will be using this ready state property and the ajax enabled web application since you can see hear index.html example we have XMLHttpRequest object. readyState propery, which is the value 4.
So before continuing what is that, take a look at possible values of XMLHttpRequest object 's readySstate property.

the possible values of readyState property are:

0 - Uninitialized
zero means XMLHttpRequest object hasnot been initialized and not ready for been used. Not ready for work and so if the readystate property is zero and you are not going to work out XMLHttpRequest object and hence it is properly initialized.

1 - Loading
one means xmlHttpRequest object is loading the data that you have requested from the server.

2 - Loaded
two means your data has been loaded the requested data that if you acquired of the server that is been loaded and its not yet complete but it been loaded the processing almost has finished

3 - Interactive
Three means that the XMLHttpRequest object it is so called in interactive state which means that the data has been downloaded by the which still you can interact with it and ask it what s type of the readystate property is. So the interactive state means the data has not yet been downloaded it is in processing in downloading so you can interact with XMLHttpRequest object

4 - Complete
Four means the download is complete and we remembered that ajax is for the asynchronous javascript and xml. Asynchronized part means that we are going to use XMLHttpRequest object to ask server send data to us and we are going to wait untill that data is complete we are not pause the browser so this is the way you check data request is complete in XMLHttpRequest object readyState property and when the property value holds for 4 that means asynchronous download of your data is complete

so that introduces the readyState property XMLHttpRequest object and you just see the following javascript code :

function doThis() {
if (request.readyState == 4) {
// do something with the response
}
}

The XMLHttpRequest Object Structure

The W3C, the organization responsible for most of the specifications we use in our web applications, is currently working on a standard definition of the XMLHttpRequest object. The latest working draft (at the time of this writing) is dated September 2006 and can be examined at http://www.w3.org/TR/XMLHttpRequest. we'll focus on the most important and common functionalities.

The XMLHttpRequest object is quite simple. The following methods are available in all of the target browsers:

open

The syntax is open(method,url[,async,username,password]). This method opens a connection to the given URL using the specified method (such as GET or POST).Optional parameters are async, a boolean value that sets the requests to be asynchronous ('true') or synchronous ('false'), and a username and password if required by the server process. If the async parameter is not provided, the request is asynchronous by default.

setRequestHeader

The syntax is setRequestHeader(label,value). This method adds a label/value pair to the header in the request.

If you are sending data to the server with a POST request, you need to set the value of the "Content-type" header to "application/x-www-form-urlencoded":

A Ajax POST request looks like this:

var request = getHTTPObject();
if (request) {
request.onreadystatechange = doThis;
request.open("POST", "serv.asp", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("name=AJAX+GUY&message=Welcome+to+AJAX");
}

send

The syntax is send(content). This method is used to send the request with any associated data. If the request is made using an HTTP method such as POST, where parameters aren't attached to the URL, all required parameters are passed using this method; otherwise, the content is set to null.

The open method specifies the details of an Ajax request, but it doesn’t initiate the request. Use the send method to fire off a request that you have prepared using the open method.

The send method takes a single argument. You can pass it a string of data that will then be sent to the server.

If you are using the GET request method, don’t send any data. Instead, pass a value of null to the send method.

A Ajax GET request looks like this:

var request = getHTTPObject();
if (request) {
request.onreadystatechange = doThis;
request.open("GET", "serv.asp", true);
request.send(null);
}

We use the POST request method to send data to the server using a query string like this:

name=AJAX+GUY&message=Welcome+to+AJAX


getAllResponseHeaders

The syntax is getAllResponseHeaders( ). This method returns all HTTP response headers as a string. Among the information included is the keepalive timeout value, content type, information about the server, and date.

getResponseHeader

The syntax is getResponseHeader(label). This method returns the specific HTTP response header identified by label.

abort

The syntax is abort( ). This method aborts the current request.



XMLHttpRequest also has the following properties:

onreadystatechange

This property holds a handle to the function that will be called when the ready state of the request changes.

If you attach a function to the onreadystatechange event handler, that

function will be executed every time the server pings the client with an

update. Here’s an example:

var request = getHTTPObject();

if (request) {

request.onreadystatechange = doThis;

}

I’m assigning a reference to a function called doThis to the

onreadystatechange event handler. The doThis function will be

executed every time the readystatechange event is triggered.

readyState

The readyState property indicates at what point the XMLHttpRequest object is with regard to sending/receiving data.
This property has one of five values:

0 for uninitialized,
1 for an open request,
2 for a request that has been sent,
3 when a response is being received,

and 4 when the response is finished loading. For the most part, we're interested in a readyState of 4.

We can compare the value of the readyState property to the number four using a simple if statement:

function doThis() {

if (request.readyState == 4) {

// do This with the response

}

}

The doThis function will be executed more than once because it has been assigned to the onreadystatechange event handler:

request.onreadystatechange = doThis;

Every time the readyState property changes, doThis is executed, but the if statement in the function ensures that nothing will happen until readyState has a value of 4.

responseText

This property specifies that the response will be formatted as a text string(a String of HTML, or XML, or just text).

function doSomething() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
alert(request.responseText);
}
}
}

The responseText property is available when the readyState property reaches four, indicating that the Ajax request is complete.

responseXML

Use this property to format the response as XML(XML document object). If the response is not XML, this property will be empty.

Implementations of XMLHttpRequest in all major browsers require the HTTP response’s Content-Type to be set properly in order for the response to be handled as XML. Well-formed XML, returned with a content type of text/xml (or application/xml, or even application/xhtml+xml), will properly populate the responseXML property of an XMLHttpRequest object; non-XML content types will result in values of null or undefined for that property.

status

This property refers to the server status, such as 304, 400, 404, 500, and 200, when the request is successful.

The most important header sent with any response from a Web server is the status code. This three-digit numerical value, which the server sends with every response to a request, is part of the HyperText Transfer Protocol (HTTP) that drives all communication on the Web. Some Status Codes are:

404 - “Not Found”

403 – “Forbidden”

500 - “Internal Server Error”

200 – “OK”

304 - “Not Modified”

In the XMLHttpRequest object, the status code sent by the server is available as a property called status. By comparing this property to a value of 200, you can be sure that the server has sent a successful response:

function doThis() {
if (request.readyState == 4) {
if (request.status == 200) {
// the response was sent successfully
}
}
}

The first if statement within the doThis function compares the readyState property to a value of 4.When that evaluates to true, meaning that the response is finished being sent, the second if statement is executed.

statusText

This property specifies the text message associated with the status.


We've gone so far, let's jump to AJAX Programming,

Here's a sample Program Using XMLHttpRequest.


Creating XMLHttpRequest Instance

XMLHttpRequest gives AJAX its true power: the ability to make asynchronous HTTP requests from the browser and pull down content in small chunks. XMLHttpRequest alllows your application to make both GET and POST requests without ever completely reloading the page.
Steps for creating AJAX class using Object Oriented Programming in JavaScript :

write a constructor function to create an instance of the class

►provide a constructor function—the name of this function is the name of your class

►add properties to the object that’s being constructed using the keyword this, followed by a period and the name of the property

►add methods to the object in the same way we’d add properties, using JavaScript’s special function constructor syntax

Here’s the code that creates a simple class called HelloAjax:

function HelloAjax () {
this.message = 'Hello, Ajax!';
this.sayMessage = function() {
window.alert(this.message);
};
}

In this example, we create a class called HelloAjax with one property (message) and one method (sayMessage). To use this class, we simply call the constructor function, as shown below:

var ha = new HelloAjax ();
ha.sayMessage();
ha.message = 'Wow…Ajax';
ha.sayMessage();

Here, we create an instance of HelloAjax (called ha), then use this object to display two messages. The first time we call sayMessage, the default “Hello, Ajax!” message is displayed. Then, after changing our object’s message property to “Wow…Ajax,” we call sayMessage and “Wow…Ajax” is displayed.

Let us examine Ajax class’s constructor function: File: ajax.js (excerpt)

function Ajax() {
this.req = null;
this.url = null;
this.method = 'GET';
this.async = true;
this.status = null;
this.statusText = '';
this.postData = null;
this.readyState = null;
this.responseText = null;
this.responseXML = null;
this.handleResp = null;
this.responseFormat = 'text', // 'text', 'xml', or 'object'
this.mimeType = null;
}

The above code defines the properties we’ll need in our Ajax class in order to work
with XMLHttpRequest objects.

Create an Instance

Creating a new instance of an XMLHttpRequest object, In IE 7, Firefox, Safari, and Opera, the syntax needed to create an object is as follows:

var xhr = new XMLHttpRequest();

In Internet Explorer,You need to create a new instance of an ActiveX object:

var xhr = new ActiveXObject("Microsoft.XMLHTTP");

if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
}

This is called object detection. Here’s the object detection to test for the existence of ActiveX:

if (window.ActiveXObject) {

var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

To save yourself from writing this every time you want to do some Ajax, you can wrap up the object detection in a reusable function:

function getHTTPObject() {

var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}

The function, called getHTTPObject, begins by declaring a variable called xhr and assigning it a Boolean value of false. The plan is to change this value over the course of the function.An if...else statement takes care of the object detection. First, test for the existence of the native XMLHttpRequest. If such an object exists, change the value of xhr to a new instance of the object. If not, test for the existence of ActiveXObject. If that exists, assign a new instance of Microsoft’s
XMLHTTP ActiveX object to xhr. Finally, return the value of xhr at the end of the function. At this stage, there are three possible values that the variable could have:

■ An instance of the native XMLHttpRequest object.

■ An instance of an ActiveX object.
■ A value of false.

You can use the function like this:

var request = getHTTPObject();

This assigns the result of the getHTTPObject function to the variable request. You can now treat this variable as an instance of a cross-browser XMLHttpRequest object. It is still possible that the getHTTPObject function has returned a value of false, meaning that the browser executing the script does not have Ajax capabilities. If you explicitly check for this, you can make sure you won’t be asking older browsers to execute code beyond their ability:

var request = getHTTPObject();
if (request) {
// do some Ajax
}

We can use the XMLHttpRequest in two ways: synchronously or asynchronously.

Synchronous Usage

You can use the XMLHttpRequest object synchronously with the following pattern:

1. Create the object.
2. Create a request.
3. Send the request.
4. Hold processing until you get a response.

This corresponds to what you normally do when you send a request to the server and wait for a
response. The real power, though, comes from using it asynchronously.

Asynchronous Usage

When you use the object asynchronously, you must call the object using the onreadystatechange
event. When this event is triggered, you must check the contents of the readystate property before your application can act. This means you will conform to the following pattern:

1. Create the object.
2. Set the readystatechange event to trigger a specific function.
3. Check the readyState property to see if the data is ready. If it isn’t, check again after an interval.

If it is, then carry on to the next step.

4. Open the Request.
5. Send the Request.
6. Continue processing, only interrupting it when you get a response.

The whole operation of the readystatechange event is performed behind the scenes and enables you to use the XMLHttpRequest object asynchronously.


Useful Links on Adobe Flex

Your Ad Here

Latest Books on Adobe Flex