XML
  Home arrow XML arrow Page 6 - XML in the Browser: Submitting forms using...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML

XML in the Browser: Submitting forms using AJAX
By: Chris Root
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 187
    2005-04-25

    Table of Contents:
  • XML in the Browser: Submitting forms using AJAX
  • What's Out There Now
  • The XML in HTTPRequest
  • HTTP Methods
  • Using POST
  • Submitting a Form

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    XML in the Browser: Submitting forms using AJAX - Submitting a Form


    (Page 6 of 6 )

     

    Normally forms don't need any additional code to submit information, aside from any validation code that you choose to use. In this case, however, we will need to write some code to gather information from the form, and possibly from other areas of the application, to put into the proper format. One advantage this has over normal form submission is that you can include information that is not part of the form. No hidden form fields are necessary to make this work.

     

    As an example, let's take a simple form to allow a user to request a product catalog by mail (you remember mail: paper, stamps, etc.).

     

     

    The submission can start out at the click of a button or link. The button should be a normal form button rather than a submit button because in this situation we aren't using the browser's built in form submission. When the user clicks on the form button, the "sub" function is called, which begins the processing of the information and submits it to the server.

     

    var xmlReq = null;;

    function sub(f)

    {

       var file = 'testPost.php'

       var str = getFormValues(f,"validate");

       xmlReq = getXML(file,str);

    }

    function getXML(file,str)

    {

       var doc = null

       if (typeof window.ActiveXObject != 'undefined' )

       {

           doc = new ActiveXObject("Microsoft.XMLHTTP");

           doc.onreadystatechange = displayState;

       }

       else

       {

           doc = new XMLHttpRequest();

           doc.onload = displayState;

       }

       doc.open( "POST", file, true );

       doc.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

       doc.send(str);

       return doc;

    }

     

    The HTML for the form is simple. There is no need to set any form attributes.

     

    <form>

    <label>Your Name<input type="text" id="text" name="name"></label>

    <br><br>

    <label>Your Address<input type="text" name="address"></label>

    <br><br>

    <label>

    <select id="info" name="Catalog">

    <option value="1">Full Product Catalog</option>

    <option value="2">Spring Catalog</option>

    <option value="3">Special Order Service</option>

    </select>&nbsp;&nbsp;Select The Product Catalog you Want to Receive</label>

    <br><br><br>

    <input type="button" value="Request Information" onClick="sub(this.form)">

    </form>

     

    Fields for name, address and a select menu with catalog choices are provided. We will need to loop through each form element and retrieve a value. The following code does this, and provides a way for text fields to be validated.

     

    function getFormValues(fobj,valFunc)

    {

       var str = "";

       var valueArr = null;

       var val = "";

       var cmd = "";

       for(var i = 0;i < fobj.elements.length;i++)

       {

           switch(fobj.elements[i].type)

           {

               case "text":

                    if(valFunc)

                    {

                        //use single quotes for argument so that the value of

                        //fobj.elements[i].value is treated as a string not a literal

                        cmd = valFunc + "(" + 'fobj.elements[i].value' + ")";

                        val = eval(cmd)

                    }

                    str += fobj.elements[i].name +

                     "=" + escape(fobj.elements[i].value) + "&";

                     break;

               case "select-one":

                    str += fobj.elements[i].name +

                    "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";

                    break;

           }

       }

       str = str.substr(0,(str.length - 1));

       return str;

    }

     

    This function accepts two arguments. The first is a reference to a form object, the other is the name of a validating function in the form of a string. The elements array of the form object is looped through, and a switch construct decides what to do with each of the relevant types of form elements (in this case just text and select-one). If the element is a text field, the eval function is used to call the validating function that is specified by argument two, which is sent the value of the form element.

     

    If you needed, for instance, to validate other types of elements, each in a unique way, you could include a second argument to the validating function that would be the name or type of the element, and allow the validating function to treat each element differently. The validating function could work in whatever way you wished it to, but it would be a good idea, if an error is found, to set a global variable to false. This variable could then be used to keep submission from occurring until the error was corrected. Form fields could be highlighted in some way if there was an error in them as well.

     

    In addition to sending the element value to a validating function, getFormValues assembles the values into a compatible querystring. The loop will add an extra "&" at the end of the string, which we clip off after the loop is finished. The string is then returned for use in our request.

     

    Conclusion

     

    AJAX technology can make browser based applications very close in functionality to standard desktop applications. Reference documentation for the XMLHTTPRequest object is available at XULplanet and Microsoft's MSDN website, and more information on XMLHTTPRequest, AJAX and examples of working applications are only a Web search away.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · this is just what I was looking for, but I found a few error's or something what...
       · I was using XMLHttpRequest from javascript through hidden frames to get/put to the...
       · The permissions error is caused by trying to run that script off of your own...
       · Hi,I am able to send the request to the server. But the problem is I dont know how...
       · It would be handled as any http request would be. I don't do a lot of JSP but I...
       · I almost forgot. JSP has a Request object for recieving the request. The...
       · Hi: How can i upload a file using the ajax form method ??? thanks for your...
       · You mention in XML in the Browser: Submitting forms using AJAX - HTTP Methods...
       · request = new ActiveXObject("Microsoft.XMLHTTP"); request.onreadystatechange =...
       · You're current script does not support radio buttons. The POST/GET will return the...
       · Great tutorial,i've used this script, and i found that it doesn't preserve special...
       · The W3C specifications state that any form object that is disabled cannot be...
       · Hi, the radio part of the last post is not working for me. I'm getting a Javascript...
       · I'm having the same problem.. Any solutions? Thanks!
       · Hello,This is how I made the radio button case work correctly in IE 6 sp2....
       · Sorry about that, as I said, I never tried out all the types. Thanks for pointing it...
       · I have done some testing and have found multiple selects don't work correctly...
       · But where is the displayState function that is needed to get the values returned...
       · That would be your AJAX script which this article does not address. Whatever you are...
       · At least as far as i know...Please correct me if I'm wrong.
       · Hmm this new GetFormValues function made my code stop working..Not sure why at...
       · Ahh got it working..Thanks heaps for your code. Much appreciated, saved me lots...
       · Hello,Could you please send a link to the complete script.Thanx in...
       · My changed version with testing html...
     

    XML ARTICLES

    - Using Regions with XSL Formatting Objects
    - Using XSL Formatting Objects
    - More Schematron Features
    - Schematron Patterns and Validation
    - Using Schematron
    - Datatypes and More in RELAX NG
    - Providing Options in RELAX NG
    - An Introduction to RELAX NG
    - Path, Predicates, and XQuery
    - Using Predicates with XQuery
    - Navigating Input Documents Using Paths
    - XML Basics
    - Introduction to XPath
    - Simple Web Syndication with RSS 2.0
    - Java UI Design with an IDE







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek