Sei sulla pagina 1di 10

15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.

htm

IT Professionals Developers Solutions eBook Library Webopedia Login Register

Data Access | Troubleshooting | Security | Performance | ADSI |


Upload | Email | Control Building | Component Building | Forms |
XML | Web Services | ASP.NET | .NET Features | .NET 2.0 |
App Development | App Architecture | IIS | Wireless

Pioneering Active Server


Search
Power Search

CodeMash 2011: DotNetNuke with Shaun Walker - Watch the Microsoft WebMatrix Launch Event Now!

Client Side Validation Using the Rating: 3.6 out


XMLHTTPRequest Object of 5
By Jonathan Zufi Rate this article

print this article


email this article to a colleague
suggest an article
Subscribe Now!
Free Newsletter Introduction
Microsoft Tech Daily
As an avid reader of 15 seconds,
I've been exposed to many articles
Subscribe! on form validation. Form validation
should not only address checking
fields for content and structure, it
Reference
should also handle real-time
News
lookups on data. This article shows
Articles
how Microsoft's
Archive
XMLHTTPRequest component can
Writers
give your users a cleaner and
Code Samples
more efficient Web experience by
Components
improving form validation.
Tools
FAQ
Programming for HTTP
Feedback
Books
There have always been several
Links
ways of making HTTP calls on the
DL Archives
Win32 platform. Visual Basic and
Community
C++ developers could leverage
Messageboard
the WinInet library, and Visual
List Servers
Basic programmers could utilize Article: Moving a Document to the
Mailing List SharePoint 2010 Records Center
the Internet Controls that shipped
WebHosts In this article, we are going to build on
with Visual Basic 6.0. However,

1 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

Consultants ASP developers have had a bit the solution we have been working
Tech Jobs more work getting access to this with over the last couple of weeks. You
15 Seconds can review Part 1 and/or Part II at your convenience. In
functionality, since they would this installment, we are going to set up a simple
Home need to wrap it in a custom one-step approval for the form and move it to a
Site Map component for elegant interaction SharePoint 2010 Records Center once the form
Press processing is complete.
with ASP code. 'Raw' scripting Moving a Document to the SharePoint 2010 Records
Legal makes the task difficult. Center
Privacy Policy Learn to set up a simple one-step approval for the form
internet.commerce Most people assume HTTP is a and move it to a SharePoint 2010 Records Center
once the form processing is complete. >>
Calling Cards protocol reserved for browsers to
Phone Cards communicate with Web servers.
Prepaid Calling Card Remember, HTTP is just a
Article: Using the Event Handler in
Prepaid Phone Card protocol, and a powerful one at
SharePoint 2010
Website Hosting that. HTTP can be used by any As organizations increase their use of
Business Liability application to talk to another SharePoint, users need more
customized forms of solutions to
IT Legal Contracts application or component; it
address their requirements. One such
Liability Insurance doesn't have to be a browser or a requirement is this: Whenever a Microsoft Word
Promote Your Website Web server. As Web developers, document is added to a document library, users want
an exclusive "Tasks" list specifically for this document.
Cell Phones we are all familiar with the
Using the Event Handler in SharePoint 2010
Desktop Computers benefits of using the HTTP As organizations increase their use of SharePoint,
PDA Phones & Cases protocol. It works well across users need more customized forms of solutions to
address their requirements. Learn how to handle such
Televisions firewalls, is based on Internet
requests. >>
Virtual Server standards, etc.
VPS Hosting
Host your Site Microsoft included the
XMLHTTPRequest component in Article: Special Report: The
Site Hosting Definitive Guide to Windows Phone 7
Web Hosting its XML toolkit so XML documents Microsoft announced Windows Phone
could be passed around over the 7 in February, 2010 at Mobile World
Internet using the standard HTTP Congress in Spain. It became
internet.com
immediately apparent that the new
IT protocol. While all the announcement was a big one. In a word, the upcoming
Developer documentation speaks of XML Windows Phone 7 is unlike any previous mobile
interchange over HTTP, the nice Windows version.
Internet News
The Definitive Guide to Windows Phone 7
Small Business thing about this component is that The upcoming Windows Phone 7, announced by
Personal Technology you don't have to deal with XML at Microsoft in Spain in February, is unlike any previous
all to leverage its power. Only a mobile Windows version. >>

Search internet.com few lines of code are necessary to


Advertise make a HTTP call and capture the
Corporate Info results. This makes the
Newsletters XMLHTTPRequest component an
Tech Jobs extremely powerful tool in every
E-mail Offers Web developer's arsenal,
especially ASP developers. MARKETPLACE

XMLHTTPRequest and
XMLHTTP
Compare products,
prices, and stores at
The XMLHTTPRequest component
Hardware Central!
is part of MSXML, which ships
Business On Main: Online Community
with Internet Explorer 5.0 and
Free Online Tools and Resources To Help Start
higher. This makes it an even more Or Grow Your Business. Join Today!
attractive tool. The core object www.BusinessOnMain.com
inside XMLHTTPRequest is the
XMLHTTP object. There are
different versions of the
XMLHTTP object, since it's been
included in every version of the
Microsoft MSXML package. For a good overview of the latest versions and

2 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

installation issues, see the Microsoft knowledge base article Q278969.

The XMLHTTP object provides all of your Web browser's communication


functionality with just a handful of methods and properties. To use this object, create
the XMLHTTP object, call the open method with the URL you want to talk to, the
type of call to make (GET, POST), and then invoke the send method. The object will
basically act like a browser and retrieve the data from the URL, making it available in
the responseText property. You can also make synchronous or asynchronous calls.
There is also a callback facility available for asynchronous calls. Very neat and very
simple.

Using XMLHTTP to perform real time data validation

Say that you are capturing user registration details for your Web site, and one of the
fields is 'User ID'. This User ID obviously needs to be unique across your site, so you'll
have a requirement to ensure that the User ID supplied at registration time does not
already exist. If it does, you'll need to warn the user and ask them to re-enter it.

The common way of dealing with this type of requirement is to apply the lookup logic
when the form is posted. However, this can sometimes lead to what is not the best
user experience. We all know how frustrating it is to continually submit forms only to
find that we have forgotten a value here or there. The other downside of posting the
page is that if it needs to be re-rendered with the appropriate 'please correct this
problem' messages, that's another trip to the server, images, script and all.

The ideal way to handle this is to alert users as soon as they have entered their
username as to whether or not it is unique. On a desktop app, this would be simple -
put some code in the 'lost focus' event of the text box. Javascript and the XMLHTTP
object can provide the same level of interaction.

Let's walk through an example, registering with a fictitious company.

The HTML for the User ID field looks like this:

<input type="text" name="UserID" onblur="validateuserid(this.value);">

3 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

The 'onblur' event will fire our validation routine when the user tabs out of the User
ID textbox. (Note: if you're not a fan of focus driven validation, you could move this to
the onclick event of the Register button).

Examine the JavaScript that performs the validation:

<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">


function validateuserid(suserid) {

document.body.style.cursor='wait';

// Create an instance of the XML HTTP Request object


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

// Prepare the XMLHTTP object for a HTTP POST to our validation ASP page
var sURL = "http://mysite/mypath/validateuser.asp?username=" + suserid
oXMLHTTP.open( "POST", sURL, false );

// Execute the request


oXMLHTTP.send();

if (oXMLHTTP.responseText == "exists")
alert("Sorry - the User ID " + suserid + " already exists.");

document.body.style.cursor='auto';
}
</SCRIPT>

Let's go through the script block in detail to see what its doing:

document.body.style.cursor='wait';

The script is going to make a HTTP call, which might take a second or two, so this
line changes the mouse to an hourglass to give the user some feedback. From the user
experience point of view, there are prettier things you can do with the UI other than
changing the mouse pointer. Javascript and DHTML give you everything you need. In
fact, there is a much more elegant way to handle this, which we'll examine later on.

// Create an instance of the XML HTTP Request object


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

This creates an instance of the XMLHTTP object.

// Prepare the XMLHTTP object for a HTTP POST to our validation ASP page
var sURL = "http://mysite/mypath/validateuser.asp?userid=" + suserid
oXMLHTTP.open( "GET", sURL, false );

The 'open' method prepares the request that we are about to make. The first
parameter defines the connection to use. In this case, we'll use the GET method.
'open' supports other methods such as PUT and POST. (POST is VERY powerful,
because as implied, you can programmatically post forms as well). The next
parameter specifies the URL that we are connecting to. Since we are running this
script on the client, this should be an absolute URL. Here we construct a call to a

4 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

custom ASP page which will tell us whether or not the User ID exists (more on this in
a moment).

The third parameter is used to tell the object whether or not to make the call
asynchronously. I've set this to False, indicating that we want to wait until the call
returns before continuing.

There are two other optional parameters, username and password. These allow a
connection to a site that requires username/password authentication.

Now that we have prepared the request, we just need to send it.

// Execute the request


objXMLReq.send();

At this point the object will actually go out over the Internet and bring back the
contents of the target page. Now we check those contents to see what happened:

if (objXMLReq.responseText == "exists")
alert("Sorry - the User ID " + suserid + " already exists.");

If the User ID has already been assigned to another user, the page returns the word
'exists' to indicate that the user id already exists in the database. (You could use any
protocol you like - for example, the ASP page could have returned a number.) Finally
we reset the cursor.

document.body.style.cursor='auto';

Now let's look at the ASP page that the script is communicating with to do the lookup:

<%
Dim objConn, objRS, sUserID

'Capture the username that we need to lookup, making sure its prepared for
'our forthcoming SQL query
sUserID = Replace(Trim(Request.QueryString("userid")),"'","")

'Fire up ADO - ask the database whether or not the user idexists
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open CONNECTIONSTRING
sSQL = "select userid from usertable where userid = '" + sUserID + "'"
Set objRS = objConn.Execute(sSQL)
If Not objRS.EOF Then Response.Write "exists"

'Clean up
objRS.Close
objConn.Close
Set objRS = Nothing
Set objConn = Nothing
%>

This is a straightforward piece of ASP code that writes out the word 'exists' if the
passed-in User ID was found in the database. If you ran this page on its own, the

5 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

browser would be blank if the User ID did not exist -- the page would just say the
word 'exists' if it did exist. This means that you can test your ASP page in isolation
before you integrate it back with your client script.

Dealing with timeouts

The first issue that has probably crossed your mind is 'what if the remote site is down
- how do I handle timeouts and errors?' While trapping an error from the 'send'
method is feasible, this doesn't fix the time the user would have to wait while the call
is being made.

Recall the third parameter on the 'open' method of the XMLHTTP object. We set it to
'false'. Setting it to 'true' will make the call immediately, and the control will drop
through to the next line, so you need to either poll or be notified (i.e. event) that the
call has completed (successfully or not). Luckily, the XMLHTTP object can notify the
function of your choice as it moves through its various stage of processing the HTTP
request. Let's have a look at a slightly modified version of the client side script that
deals with potential timeouts:

<!-define a div that will be our pseudo progress indicator -->


<div id="divProgress">Please wait</div>

<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">


// Create an instance of the XML HTTP Request object
var oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );
var userid;
function validateuserid(suserid) {

// Prepare the XMLHTTP object for a HTTP POST to our validation ASP page
userid = suserid;
var sURL = " http://mysite/mypath/validateuser.asp?userid=" + userid;
oXMLHTTP.open( "POST", sURL, false );

// Define an event handler for processing


oXMLHTTP.onreadystatechange = managestatechange;

// Execute the request


try {
oXMLHTTP.send();
}
catch (e) {
alert("Could not validate your User ID at this time.");
document.all.item("FirstName").focus;
}
}

function managestatechange() {
switch (oXMLHTTP.readyState) {

case 2, 3:
// Display a progress indicator of some kind, informing the
// user that you are checking to see if the UserID exists
document.all.item("divProgress").style.display = "block";
break;

case 4:
if (oXMLHTTP.responseText == "exists")
alert("Sorry - the User ID " + userid + " already exists.");
document.all.item("divProgress").style.display = "none";

6 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

break;
}
}

// Hide the progress indicator for now


document.all.item("divProgress").style.display = "none";

</script>

The code of interest here is line where we set the event handler:

// Define an event handler for processing


oXMLHTTP.onreadystatechange = managestatechange;

This tells the XMLHTTP object to call the 'managestatechange' function as it the
state of the HTTP request changes - from the time the object is created until the point
where the request has completed. There are five different states that you can
monitor:

0 The object has been created, but not initialized


(UNINITIALIZED) (open method has not been called).
The object has been created, but the send
(1) LOADING
method has not been called.
The send method has been called and the status
(2) LOADED and headers are available, but the response is
not yet available.
Some data has been received. You can call
(3) INTERACTIVE responseBody and responseText to get the
current partial results.
All the data has been received, and the
(4) COMPLETED complete data is available in responseBody and
responseText.

- from MSDN

In the updated script, I also make it a little more robust by adding some error
handling. After all, the remote site may be down or the page may not exist:

// Execute the request


try {
oXMLHTTP.send();
}
catch (e) {
alert("Could not validate your User ID at this time.");
document.all.item("FirstName").focus;
}

When the code in the callback function is finished, the control will return to the
calling routine, and if a problem occurred, you can cater for it. Note that I set the
focus to another field. This is important, otherwise the user would never be able to
move out of the User ID field.

7 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

It is useful to note at this stage that there is another component called the
ServerXMLHTTP object - see the Microsoft knowledge base article Q290761 for
details about the differences between these two components. ServerXMLHTTP, as
the name implies, is more suited for HTTP connectivity from the server end and is a
little more elegant when dealing with timeouts. This is useful to know if you want to
do some bigger and better things. This article was focused on client side validation so
we focused on the XMLHTTP object since it was actually designed and optimized to
be a client side component.

I hope this article has shown you how powerful the XMLHTTPRequest object from
Microsoft is. Check out the MSDN Web site for more examples.

About the Author

Jonathan Zufi is the founder of UDU World (http://www.uduworld.com), a company


that sells solutions based on their ActiveInbox technology. ActiveInbox is a back end
information and content delivery platform that provides information access over
email and mobile text messaging.

Jonathan has been developing software for over ten years. He holds an Honour's
degree in Robotics and Digital Technology from Monash University (Melbourne,
Australia). He was recently awarded the Pearcey Award from the Australia
Computer Society, which recognizes innovative and pioneering achievement and
contribution to research and development in Information and Computer Technology
across Australia. Jonathan may be reached at jonathanzufi@UDUworld.com

Rate This Article


Not Helpful Most Helpful
1 2 3 4 5

submit

Supporting Products/Tools
Stonebroom.ASP2XML
Stonebroom.ASP2XML(c) is an interface component designed to make
building applications that transport data in XML format much easier. It can be
used to automatically pass updates back to the original data source.
[Top]

Other Articles
Nov 6, 2001 - Writing Your Own Script File to Migrate a
Database
Learn how to write a script file using SQL Server's Bulk Copy Program for
easy and speedy database migration.
[Read This Article] [Top]

Sep 5, 2001 - Firing Events in a Shared Hosting


Environment
Firing events on a Web server is an easy task. However most of the easy
solutions require you to have your own dedicated IIS or SQL Server on the
Internet to play with, a privilege not shared by many. In this article, Matthew

8 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

Muller shows you how to get the same functionality in a shared hosting
environment.
[Read This Article] [Top]

Jun 26, 2001 - Dynamically Changing Static Web Galleries


Web galleries are an easy way to add interactivity and content to your Web
site. However, how do you keep the Web galleries consistent with your site and
how do you overcome the deficiencies of your Web gallery creation tool? John
Sorensen explains a simple way to do both.
[Read This Article] [Top]

Jun 8, 2001 - Implementing Dynamic Arrays of Objects


Using classes in ASP 3.0 we can create dynamic arrays of objects. Donnell
DeLeon Smith's article also shows how we can implement a class of dynamic
arrays of objects several layers deep, if required.
[Read This Article] [Top]

Mar 27, 2001 - Using ASP to Send a Wireless Text Message


Even though SMS is now in high gear, developers remain slated with restrictive
limits to carrier resources. Sending an SMS message via e-mail requires the
acceptance of several hidden flaws. Joe Lauer shows how to avoid these
complications by sending a wireless text-message through the use of ASP.
[Read This Article] [Top]

Mar 1, 2001 - Server-Side Validations Using Regular


Expressions
Add punch to your validation routines by adding regular expressions. Further
prepare yourself for the coming ASP.NET regular expression validation control.
This article shows you how to use regular expressions and provides sample
patterns for different user inputs.
[Read This Article] [Top]

Sep 20, 2000 - How to Display File ACLs on Your Web Page
without Active Directory
Thought displaying file ACLs on a Web page in a browser was impossible
without Active Directory installed? Think again. Through a patchwork of
technologies, Larry Schwartz proves otherwise.
[Read This Article] [Top]

Aug 11, 2000 - Servers-Side Validations on the Client Side


Servers-side validations on the client side...isn't that an oxymoron? Maybe, but
Pandurang Nayak shows us how to accomplish a type of remote scripting using
a mix of Javascript and ASP.
[Read This Article] [Top]

Aug 3, 2000 - Recursive Functions


A function that calls itself repeatedly, satisfying some condition is called a
Recursive Function. Using recursion, we split a complex problem into its single
simplest case. The recursive function only knows how to solve that simplest
case. You'll see the difference between solving a problem iteratively and
recursively later.
[Read This Article] [Top]

Jul 27, 2000 - Effect of Using Multiple Scripting Languages


in ASP

9 of 10 01/21/2011 06:15 PM
15 Seconds : Client Side Validation Using the XM... http://www.15seconds.com/issue/020606.htm

Do you know what happens when you use multiple languages within your ASP
page? Gopikrishna S throws light on how an ASP page behaves when multiple
languages are used for server side scripting.
[Read This Article] [Top]

Mailing List
Want to receive email when the next article is published? Just Click Here to sign up.

Support the Active Server Industry

The Network for Technology Professionals

Search:

About Internet.com
Copyright 2011 QuinStreet Inc. All Rights Reserved.

Legal Notices, Licensing, Permissions, Privacy Policy.


Advertise | Newsletters | E-mail Offers

Solutions
Whitepapers and eBooks
New: Built-in Developer Tools on Internet Explorer 9 PHP for Windows Showcase
5 Ways Site Pinning Will Transform Websites Resource: PHP for Windows Showcase
HTML5: Create Visually Pleasing Content for Your Sites and Apps MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Let Your Sites Shine: Web Content Can Now Come Forward

Webcasts
On Demand Webcast: Essentials for Managing Your SAP Applications Software License Operations - Cleaning Up the Backoffice
Video: Unlock the Processing Power of Your PC MORE WEBCASTS, PODCASTS, AND VIDEOS
Spend Less Time Rewriting Your Sites to Work Across Browsers

Downloads and eKits


Microsoft Download: Windows API Code Pack MORE DOWNLOADS, EKITS, AND FREE TRIALS
New: Internet Explorer 9 Beta -- Download Now!

Tutorials and Demos


Unlock the Processing Power of Your PC Internet.com Hot List: Get the Inside Scoop on IT and Developer Products
Exceptional Web Experiences MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES

10 of 10 01/21/2011 06:15 PM

Potrebbero piacerti anche