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 Upload XML

|

Troubleshooting

|

Security

|

Performance

| |

Email

|

Control Building

| |

Component Building .NET Features

| |

ADSI Forms

| |

Web Services

| |

ASP.NET

|

.NET 2.0 Wireless

|

App Development

App Architecture

|

IIS

|

Pioneering Active Server

Search
Power Search

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

Client Side Validation Using the XMLHTTPRequest Object By Jonathan Zufi
print this article email this article to a colleague suggest an article

Rating: 3.6 out of 5 Rate this article

Subscribe Now! Free Newsletter
Microsoft Tech Daily

Introduction
As an avid reader of 15 seconds, I've been exposed to many articles on form validation. Form validation should not only address checking fields for content and structure, it should also handle real-time lookups on data. This article shows how Microsoft's XMLHTTPRequest component can give your users a cleaner and more efficient Web experience by improving form validation.

Subscribe!
Reference News Articles Archive Writers Code Samples Components Tools FAQ Feedback Books Links DL Archives Community Messageboard List Servers Mailing List WebHosts

Programming for HTTP
There have always been several ways of making HTTP calls on the Win32 platform. Visual Basic and C++ developers could leverage the WinInet library, and Visual Basic programmers could utilize the Internet Controls that shipped with Visual Basic 6.0. However,

Article: Moving a Document to the SharePoint 2010 Records Center In this article, we are going to build on

1 of 10

01/21/2011 06:15 PM

users want an exclusive "Tasks" list specifically for this document. It works well across firewalls. >> Article: Special Report: The Definitive Guide to Windows Phone 7 Microsoft announced Windows Phone 7 in February. is based on Internet standards.. Microsoft included the XMLHTTPRequest component in its XML toolkit so XML documents could be passed around over the Internet using the standard HTTP protocol. Using the Event Handler in SharePoint 2010 As organizations increase their use of SharePoint. As Web developers. >> Article: Using the Event Handler in SharePoint 2010 As organizations increase their use of SharePoint. 'Raw' scripting makes the task difficult.com attractive tool. >> MARKETPLACE Compare products. especially ASP developers. Learn how to handle such requests. and a powerful one at that. 2010 at Mobile World Congress in Spain. the solution we have been working with over the last couple of weeks. In this installment.commerce Calling Cards Phone Cards Prepaid Calling Card Prepaid Phone Card Website Hosting Business Liability IT Legal Contracts Liability Insurance Promote Your Website Cell Phones Desktop Computers PDA Phones & Cases Televisions Virtual Server VPS Hosting Host your Site Site Hosting Web Hosting internet.com/issue/020606. http://www. One such requirement is this: Whenever a Microsoft Word document is added to a document library. users need more customized forms of solutions to address their requirements. For a good overview of the latest versions and 2 of 10 01/21/2011 06:15 PM . is unlike any previous mobile Windows version. Only a few lines of code are necessary to make a HTTP call and capture the results.0 and Free Online Tools and Resources To Help Start higher. It became immediately apparent that the new announcement was a big one. we are going to set up a simple one-step approval for the form and move it to a SharePoint 2010 Records Center once the form processing is complete. This makes it an even more Or Grow Your Business. HTTP can be used by any application to talk to another application or component. etc. Moving a Document to the SharePoint 2010 Records Center Learn to set up a simple one-step approval for the form and move it to a SharePoint 2010 Records Center once the form processing is complete.15seconds. There are different versions of the XMLHTTP object.15 Seconds : Client Side Validation Using the XM. since it's been included in every version of the Microsoft MSXML package. users need more customized forms of solutions to address their requirements. since they would need to wrap it in a custom component for elegant interaction with ASP code. announced by Microsoft in Spain in February.htm Consultants Tech Jobs 15 Seconds Home Site Map Press Legal Privacy Policy internet. and stores at Hardware Central! XMLHTTPRequest and XMLHTTP The XMLHTTPRequest component is part of MSXML.. which ships Business On Main: Online Community with Internet Explorer 5. In a word.com Advertise Corporate Info Newsletters Tech Jobs E-mail Offers ASP developers have had a bit more work getting access to this functionality. it doesn't have to be a browser or a Web server. You can review Part 1 and/or Part II at your convenience. Most people assume HTTP is a protocol reserved for browsers to communicate with Web servers. Remember. The Definitive Guide to Windows Phone 7 The upcoming Windows Phone 7. The core object inside XMLHTTPRequest is the XMLHTTP object. While all the documentation speaks of XML interchange over HTTP. This makes the XMLHTTPRequest component an extremely powerful tool in every Web developer's arsenal. prices. HTTP is just a protocol. the upcoming Windows Phone 7 is unlike any previous mobile Windows version.com IT Developer Internet News Small Business Personal Technology Search internet.BusinessOnMain. Join Today! www. we are all familiar with the benefits of using the HTTP protocol. the nice thing about this component is that you don't have to deal with XML at all to leverage its power.

registering with a fictitious company. so you'll have a requirement to ensure that the User ID supplied at registration time does not already exist. If it does.com/issue/020606.15 Seconds : Client Side Validation Using the XM. see the Microsoft knowledge base article Q278969. There is also a callback facility available for asynchronous calls. 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. The object will basically act like a browser and retrieve the data from the URL. create the XMLHTTP object. The XMLHTTP object provides all of your Web browser's communication functionality with just a handful of methods and properties. script and all. that's another trip to the server. and then invoke the send method. The other downside of posting the page is that if it needs to be re-rendered with the appropriate 'please correct this problem' messages. and one of the fields is 'User ID'. However. this can sometimes lead to what is not the best user experience. Using XMLHTTP to perform real time data validation Say that you are capturing user registration details for your Web site.. We all know how frustrating it is to continually submit forms only to find that we have forgotten a value here or there. The common way of dealing with this type of requirement is to apply the lookup logic when the form is posted. To use this object.value). call the open method with the URL you want to talk to. http://www. this would be simple put some code in the 'lost focus' event of the text box. images. The HTML for the User ID field looks like this: <input type="text" name="UserID" onblur="validateuserid(this. Let's walk through an example. the type of call to make (GET. This User ID obviously needs to be unique across your site.15seconds. On a desktop app.. Javascript and the XMLHTTP object can provide the same level of interaction. You can also make synchronous or asynchronous calls. Very neat and very simple. making it available in the responseText property."> 3 of 10 01/21/2011 06:15 PM . you'll need to warn the user and ask them to re-enter it.htm installation issues. POST).

com/issue/020606. which might take a second or two. there are prettier things you can do with the UI other than changing the mouse pointer. The next parameter specifies the URL that we are connecting to. In this case. this should be an absolute URL..send().").the User ID " + suserid + " already exists. This creates an instance of the XMLHTTP object.cursor='wait'. sURL. 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.htm The 'onblur' event will fire our validation routine when the user tabs out of the User ID textbox. sURL. From the user experience point of view.asp?userid=" + suserid oXMLHTTP. } </SCRIPT> Let's go through the script block in detail to see what its doing: document. Here we construct a call to a 4 of 10 01/21/2011 06:15 PM . The first parameter defines the connection to use. because as implied. 'open' supports other methods such as PUT and POST. (Note: if you're not a fan of focus driven validation. there is a much more elegant way to handle this.cursor='wait'.. In fact.style. // Prepare the XMLHTTP object for a HTTP POST to our validation ASP page var sURL = "http://mysite/mypath/validateuser. false ). if (oXMLHTTP.style. The 'open' method prepares the request that we are about to make. The script is going to make a HTTP call.body.style.15seconds. // Prepare the XMLHTTP object for a HTTP POST to our validation ASP page var sURL = "http://mysite/mypath/validateuser. Since we are running this script on the client.asp?username=" + suserid oXMLHTTP.open( "GET". // Create an instance of the XML HTTP Request object var oXMLHTTP = new ActiveXObject( "Microsoft. Javascript and DHTML give you everything you need. you can programmatically post forms as well). // Create an instance of the XML HTTP Request object var oXMLHTTP = new ActiveXObject( "Microsoft.15 Seconds : Client Side Validation Using the XM. // Execute the request oXMLHTTP.XMLHTTP" ). which we'll examine later on.responseText == "exists") alert("Sorry .XMLHTTP" ).cursor='auto'. we'll use the GET method. false ).open( "POST". http://www. (POST is VERY powerful. so this line changes the mouse to an hourglass to give the user some feedback.body.body. document.

CreateObject("ADODB. the 5 of 10 01/21/2011 06:15 PM . The third parameter is used to tell the object whether or not to make the call asynchronously. At this point the object will actually go out over the Internet and bring back the contents of the target page."'".15 Seconds : Client Side Validation Using the XM. These allow a connection to a site that requires username/password authentication. (You could use any protocol you like . There are two other optional parameters.htm custom ASP page which will tell us whether or not the User ID exists (more on this in a moment)."") 'Fire up ADO ."). the page returns the word 'exists' to indicate that the user id already exists in the database. I've set this to False.Write "exists" 'Clean up objRS.EOF Then Response.the User ID " + suserid + " already exists.15seconds.Close objConn.ask the database whether or not the user idexists Set objConn = Server.style. If the User ID has already been assigned to another user.) Finally we reset the cursor.Open CONNECTIONSTRING sSQL = "select userid from usertable where userid = '" + sUserID + "'" Set objRS = objConn.responseText == "exists") alert("Sorry .send().com/issue/020606. sUserID 'Capture the username that we need to lookup. Now we check those contents to see what happened: if (objXMLReq. document. Now that we have prepared the request. http://www. the ASP page could have returned a number.QueryString("userid")). // Execute the request objXMLReq.Connection") objConn. If you ran this page on its own.for example.cursor='auto'.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.body. objRS. indicating that we want to wait until the call returns before continuing. Now let's look at the ASP page that the script is communicating with to do the lookup: <% Dim objConn... making sure its prepared for 'our forthcoming SQL query sUserID = Replace(Trim(Request. we just need to send it.Execute(sSQL) If Not objRS. username and password.

item("divProgress"). var sURL = " http://mysite/mypath/validateuser.send().htm browser would be blank if the User ID did not exist -. 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.onreadystatechange = managestatechange.item("FirstName"). false ). Recall the third parameter on the 'open' method of the XMLHTTP object. var userid. Dealing with timeouts The first issue that has probably crossed your mind is 'what if the remote site is down .open( "POST". this doesn't fix the time the user would have to wait while the call is being made.").all.the User ID " + userid + " already exists. document.the page would just say the word 'exists' if it did exist. 6 of 10 01/21/2011 06:15 PM . sURL. } catch (e) { alert("Could not validate your User ID at this time.XMLHTTP" ).all. http://www.asp?userid=" + userid.display = "none". We set it to 'false'.focus. and the control will drop through to the next line.all.style. document. 3: // Display a progress indicator of some kind. case 4: if (oXMLHTTP. informing the // user that you are checking to see if the UserID exists document.display = "block". // Execute the request try { oXMLHTTP. break..15seconds.responseText == "exists") alert("Sorry . This means that you can test your ASP page in isolation before you integrate it back with your client script.how do I handle timeouts and errors?' While trapping an error from the 'send' method is feasible. Luckily. } } function managestatechange() { switch (oXMLHTTP."). Setting it to 'true' will make the call immediately.. oXMLHTTP.item("divProgress").style. the XMLHTTP object can notify the function of your choice as it moves through its various stage of processing the HTTP request. // Define an event handler for processing oXMLHTTP.15 Seconds : Client Side Validation Using the XM. event) that the call has completed (successfully or not). function validateuserid(suserid) { // Prepare the XMLHTTP object for a HTTP POST to our validation ASP page userid = suserid.com/issue/020606.readyState) { case 2. so you need to either poll or be notified (i.e.

all. } When the code in the callback function is finished.focus. You can call (3) INTERACTIVE responseBody and responseText to get the current partial results. 7 of 10 01/21/2011 06:15 PM . the control will return to the calling routine. but not initialized (UNINITIALIZED) (open method has not been called).item("divProgress"). the remote site may be down or the page may not exist: // Execute the request try { oXMLHTTP. document. After all.com/issue/020606. </script> The code of interest here is line where we set the event handler: // Define an event handler for processing oXMLHTTP.from the time the object is created until the point where the request has completed. This is important. I also make it a little more robust by adding some error handling..display = "none"."). } catch (e) { alert("Could not validate your User ID at this time. you can cater for it. (4) COMPLETED All the data has been received.send(). The send method has been called and the status and headers are available. Note that I set the focus to another field.15seconds.style.onreadystatechange = managestatechange. (1) LOADING (2) LOADED The object has been created.all. otherwise the user would never be able to move out of the User ID field. .from MSDN In the updated script. This tells the XMLHTTP object to call the 'managestatechange' function as it the state of the HTTP request changes . http://www. and the complete data is available in responseBody and responseText. Some data has been received. and if a problem occurred.15 Seconds : Client Side Validation Using the XM. but the send method has not been called. There are five different states that you can monitor: 0 The object has been created.htm break. } } // Hide the progress indicator for now document.item("FirstName").. but the response is not yet available.

2001 . It can be used to automatically pass updates back to the original data source.Firing Events in a Shared Hosting Environment Firing events on a Web server is an easy task.uduworld.15seconds. a privilege not shared by many. is more suited for HTTP connectivity from the server end and is a little more elegant when dealing with timeouts. a company that sells solutions based on their ActiveInbox technology. Jonathan may be reached at jonathanzufi@UDUworld.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. About the Author Jonathan Zufi is the founder of UDU World (http://www. as the name implies.com/issue/020606.htm It is useful to note at this stage that there is another component called the ServerXMLHTTP object . ServerXMLHTTP. http://www.ASP2XML(c) is an interface component designed to make building applications that transport data in XML format much easier. However most of the easy solutions require you to have your own dedicated IIS or SQL Server on the Internet to play with. Check out the MSDN Web site for more examples.. [Top] Other Articles Nov 6. [Read This Article] [Top] Sep 5.see the Microsoft knowledge base article Q290761 for details about the differences between these two components.15 Seconds : Client Side Validation Using the XM. 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.ASP2XML Stonebroom.. This is useful to know if you want to do some bigger and better things. In this article.com). 2001 . ActiveInbox is a back end information and content delivery platform that provides information access over email and mobile text messaging. He was recently awarded the Pearcey Award from the Australia Computer Society. Matthew 8 of 10 01/21/2011 06:15 PM . which recognizes innovative and pioneering achievement and contribution to research and development in Information and Computer Technology across Australia.com Rate This Article Not Helpful 1 2 3 4 5 Most Helpful submit Supporting Products/Tools Stonebroom. Australia). Jonathan has been developing software for over ten years. I hope this article has shown you how powerful the XMLHTTPRequest object from Microsoft is. He holds an Honour's degree in Robotics and Digital Technology from Monash University (Melbourne.

15 Seconds : Client Side Validation Using the XM. 2001 .15seconds.com/issue/020606. Further prepare yourself for the coming ASP. Through a patchwork of technologies. but Pandurang Nayak shows us how to accomplish a type of remote scripting using a mix of Javascript and ASP. we split a complex problem into its single simplest case..Effect of Using Multiple Scripting Languages in ASP 9 of 10 01/21/2011 06:15 PM .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. [Read This Article] [Top] Jul 27. This article shows you how to use regular expressions and provides sample patterns for different user inputs...Using ASP to Send a Wireless Text Message Even though SMS is now in high gear.isn't that an oxymoron? Maybe. Joe Lauer shows how to avoid these complications by sending a wireless text-message through the use of ASP. [Read This Article] [Top] Aug 11.Implementing Dynamic Arrays of Objects Using classes in ASP 3. satisfying some condition is called a Recursive Function.NET regular expression validation control. developers remain slated with restrictive limits to carrier resources. http://www.htm Muller shows you how to get the same functionality in a shared hosting environment. Donnell DeLeon Smith's article also shows how we can implement a class of dynamic arrays of objects several layers deep. if required. The recursive function only knows how to solve that simplest case. 2001 . Larry Schwartz proves otherwise.Recursive Functions A function that calls itself repeatedly.Server-Side Validations Using Regular Expressions Add punch to your validation routines by adding regular expressions. 2000 .Dynamically Changing Static Web Galleries Web galleries are an easy way to add interactivity and content to your Web site. You'll see the difference between solving a problem iteratively and recursively later.0 we can create dynamic arrays of objects. [Read This Article] [Top] Aug 3. [Read This Article] [Top] Sep 20. 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. 2000 .Servers-Side Validations on the Client Side Servers-side validations on the client side. 2000 . [Read This Article] [Top] Jun 8. 2000 .. Using recursion. 2001 . [Read This Article] [Top] Mar 27. 2001 . [Read This Article] [Top] Jun 26. However. Sending an SMS message via e-mail requires the acceptance of several hidden flaws. [Read This Article] [Top] Mar 1.

Privacy Policy. Licensing. AND FREE TRIALS Tutorials and Demos Unlock the Processing Power of Your PC Exceptional Web Experiences Internet. DEMOS AND STEP-BY-STEP GUIDES 10 of 10 01/21/2011 06:15 PM .com Hot List: Get the Inside Scoop on IT and Developer Products MORE TUTORIALS. Permissions. EBOOKS. Advertise | Newsletters | E-mail Offers Solutions Whitepapers and eBooks New: Built-in Developer Tools on Internet Explorer 9 5 Ways Site Pinning Will Transform Websites HTML5: Create Visually Pleasing Content for Your Sites and Apps Let Your Sites Shine: Web Content Can Now Come Forward PHP for Windows Showcase Resource: PHP for Windows Showcase MORE WHITEPAPERS.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.15seconds. AND VIDEOS Downloads and eKits Microsoft Download: Windows API Code Pack New: Internet Explorer 9 Beta -.. Legal Notices. Support the Active Server Industry The Network for Technology Professionals Search: About Internet. AND ARTICLES Webcasts On Demand Webcast: Essentials for Managing Your SAP Applications Video: Unlock the Processing Power of Your PC Spend Less Time Rewriting Your Sites to Work Across Browsers Software License Operations .com/issue/020606. EKITS. [Read This Article] [Top] Mailing List Want to receive email when the next article is published? Just Click Here to sign up.Cleaning Up the Backoffice MORE WEBCASTS. All Rights Reserved.Download Now! MORE DOWNLOADS. PODCASTS..15 Seconds : Client Side Validation Using the XM. http://www.com Copyright 2011 QuinStreet Inc.