Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

XForms tip: Combining Ajax and XForms

Nicholas Chase (ibmquestions@nicholaschase.com), Freelance writer, Backstop Media
Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, an Oracle instructor, and the Chief Technology Officer of an interactive communications company. He is the author of several books, including XML Primer Plus (Sam's).

Summary:  Asynchronous JavaScript™ and XML, or Ajax, has been causing a stir in the Web world for some time now, because it enables Web designers to create an application that reacts to the user's actions without having to reload the entire page, a capability that already exists natively in XForms. This tip looks at both the XForms and Ajax versions and how to combine the two techniques. There are plenty of resources out there to teach you how to actually make Ajax requests, but XForms provides some special challenges and opportunities in using the data once you get it back.

View more content in this series

Date:  03 Oct 2006
Level:  Intermediate
Also available in:   Chinese  Korean  Russian  Japanese

Activity:  11493 views
Comments:  

Check out the Ajax Resource Center, your one-stop shop for information on the Ajax programming model, including articles and tutorials, discussion forums, blogs, wikis, events, and news. If it's happening, it's covered here.

Before you begin: Notes about this tip

This tip is specific to a particular task. For background information on XForms, see the three-part series Introduction to XForms.

The XForms samples described in this tip have been tested and work with Firefox 1.5 (with the XForms extension installed) and Microsoft® Internet Explorer 6 with the Formsplayer control installed. The download contains the XHTML file for Firefox and the HTML file for IE.


The application

XForms provides its own version of Ajax, in that it is designed to enable you to replace the data that defines the page's content without replacing the entire page. Consider, for example, a page of snippets of cowboy wisdom. The instance might look like what's shown in Listing 1.


Listing 1. The instance data

<pearls>
   <pearl>
      Never ask a barber if he thinks you need a haircut.
   </pearl>
   <pearl>
      Making it in life is kind of like busting broncos. You're 
going to get thrown a lot. The simple secret is to keep getting 
back on.
   </pearl>
   <pearl>
      Never miss a good chance to shut up.
   </pearl>
   <pearl>
      The quickest way to double your money is to fold it over and 
put it back in your pocket.
   </pearl>
</pearls>

You can then build a form that looks like this (see Listing 2).


Listing 2. The form

<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ev="http://www.w3.org/2001/xml-events" 
xmlns:xforms="http://www.w3.org/2002/xforms">
  <head>
    <title>Instance Data-To-XHTML/XForms Example</title>
    <xforms:model id="model_pearls">
      <xforms:instance id="instance_model_pearls" src="wisdom.xml"/>
      <xforms:submission id="submit_model_pearls" 
          action="http://localhost/newwisdom.xml"
          method="post" replace="instance"
          instance="instance_model_pearls"/>
    </xforms:model>
    <link href="gen_default.css" rel="stylesheet"/>
  </head>
  <body>
  
<h1>Cowboy Wisdom</h1>
   
    <xforms:output id="thePearl" ref="/pearls/pearl[2]" 
                     model="model_pearls" />

    <xforms:submit submission="submit_model_pearls">
      <xforms:label>Get new sayings</xforms:label>
    </xforms:submit>
  </body>
</html>

The result is a page much like Figure 1.


Figure 1. The basic page
basic page

Notice that the ref attribute for the output element is an XPath statement that includes position. By controlling that XPath statement, you can control what appears on the page.

You can also control the page by controlling the actual data. You may have noticed that in Listing 1, part of the bold text is information on the submission element. Here you have instructed the XForms engine to replace not the page, but a specific instance. By making a request to the URL that will return the same structure but with different data, you can immediately get new data. For example, if you click the Submit button, the browser loads another document, and because the output statement is set to always look at a particular position, that is the position for the data that will now populate the form, as you can see in Figure 2.


Figure 2. Replacing part of the page
Replacing part of the page

When you absolutely have to use a script

In some cases, however, you're going to have to use JavaScript, whether you like it or not. Perhaps you are dealing with data that must be massaged in some way before it's used, or is coming from a site you do not control. One option is to retrieve the data using JavaScript, and then add it to the page.

The key is to understand that you can't directly add data to an element the way you would with a plain HTML page. Instead, you need to put the information into the instance and then manipulate the XPath statement that specifies the contents of an XForms control.

An example of this would be to add a second button to the page to cycle through the sayings (see Listing 3).


Listing 3. Adding a script

...
  <body>
  
<h1>Cowboy Wisdom</h1>
   
  <script type="text/javascript">
      var whichPearl = 0;
      function choosePearl(){
          if (whichPearl == 0) {
            whichPearl = 1;
          } else if (whichPearl == 1) {
            whichPearl = 2;
          } else if (whichPearl == 2) {
            whichPearl = 3;
          } else if (whichPearl == 3) {
            whichPearl = 0;
          }
          refString = "/pearls/pearl["+whichPearl+"]";
          theTarget = document.getElementById("thePearl");
          theTarget.setAttribute("ref", refString);
      }
  </script>
  
 
      <xforms:output id="thePearl" ref="/pearls/pearl[2]"       
                                 model="model_pearls" />

      <form>
          <input type="button" value="Change saying" 
                                onclick="choosePearl();" />
      </form>

    <xforms:submit submission="submit_model_pearls">
      <xforms:label>Get new sayings</xforms:label>
    </xforms:submit>
  </body>
</html>

The function itself is simple, cycling through numeric values. In a real application, this would be the script in which you make your Ajax requests and deal with the data returned. For each index value, you are creating new text that goes in the ref attribute of the thePearl element.

Next you add a from which to call this script. Now if you reload the page, the button appears and you can click it. Each time you click it and the ref attribute changes, the page automatically changes the data to match that XPath statement, as you can see in Figure 3.


Figure 3. The new script
The new script

Summary

XForms already provides some Ajax-like capabilities, in that you can change the data on the page without having to reload the page itself. If, on the other hand, you must go to a script, you can manipulate the XML data that defines what the XForms form looks like, thereby making any changes you need based on external data.



Download

DescriptionNameSizeDownload method
Ajax XForms samplesxforms_ajax_source.zip4KB HTTP

Information about download methods


Resources

About the author

Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, an Oracle instructor, and the Chief Technology Officer of an interactive communications company. He is the author of several books, including XML Primer Plus (Sam's).

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML
ArticleID=164719
ArticleTitle=XForms tip: Combining Ajax and XForms
publish-date=10032006
author1-email=ibmquestions@nicholaschase.com
author1-email-cc=dwxed@us.ibm.com

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

For articles in technology zones (such as Java technology, Linux, Open source, XML), Popular tags shows the top tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), Popular tags shows the top tags for just that product zone.

For articles in technology zones (such as Java technology, Linux, Open source, XML), My tags shows your tags for all technology zones. For articles in product zones (such as Info Mgmt, Rational, WebSphere), My tags shows your tags for just that product zone.

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Try IBM PureSystems. No charge.

Special offers