LanguagesJavaScriptAdvanced Features in Creating a Double-Combo Linked List with Ajax

Advanced Features in Creating a Double-Combo Linked List with Ajax

Advanced issues

In the previous article, Creating a Double-Combo Linked List with Ajax, we built a simplified version of a double-combo script. We send a single parameter to the server, and we return a set of results for the single selected item. You may find that you need to change the way that this application works. You may want to add another element to the form so that you have a triple combo. You may even want to allow the user to select multiple items in the first list. If this is the case, then the following sections will give you ideas on how to implement them.

Allowing multiple-select queries

The code we have discussed so far is a simple example, allowing a user to select only one option from each selection list. In some cases, a user may be required to select more than one option from the first list. That means the second list in our combination will be populated with values corresponding to each selected option in the first list. With some simple changes to our client-side and server-side code, we can make this happen.

The first thing to do is to set up the first selection list to allow multiple items to be chosen. To do this, we need to add the multiple attribute to the select tag. To specify how many options to display, we can add the size attribute. If size is smaller than the number of options, the selection list will be scrollable to reveal those that are not visible.

<select name="ddlRegion" multiple size="4"
   onchange="FillTerritory(this,document.Form1.ddlTerritory)">
   <option value="1">Eastern</option>
   <option value="2">Western</option>
   <option value="3">Northern</option>
   <option value="4">Southern</option>
</select>

The next step is to change the FillTerritory() function. Instead of just referencing the selected index of the select element, we need to loop through all the options and find each of the selected values. We add the value of each selected option to the parameter string:

function FillTerritory(oElem,oTarget){
   var url = 'DoubleComboMultiple.aspx';
   var strParams = "f=" + oTarget.form.name +
      "&e=" + oTarget.name;
   for(var i=0;i<oElem.options.length;i++){
      if(oElem.options[i].selected){
         strParams += "&q=" + oElem.options[i].value;
      }
   }

   var loader1 = new
   net.ContentLoader(url,FillDropDown,null,"POST",strParams);
}

The last thing to do is change the code of the server-side script to handle the multiple values passed in the request. In .NET, the multiple values are represented in a single string, separated by commas. In order to get each item individually, we need to split the string into an array. We can then build our WHERE clause for the SQL statement by looping through the array.

Dim strQuery As String = Request.Form("q")
Dim strWhere As String = ""
Dim arrayStr() As String = strQuery.Split(",")
Dim i As Integer
For Each i In arrayStr
   If strWhere.Length > 0 Then
      strWhere = strWhere & " OR "
   End If
   strWhere = strWhere & " regionid = " & i
Next

Dim strSql As String = "SELECT " & _
           " TerritoryDescription, " & _
           " TerritoryID" & _
           " FROM Territories" & _
           " WHERE " & strWhere & _
           " ORDER BY TerritoryDescription"

With these changes, a user to can select multiple regions from the first selection list, and the territories corresponding with every selected region will appear in the second list.

Moving from a double combo to a triple combo

Moving to a double combo to a triple combo requires only a small number of changes, depending on how we want to handle the logic on the server. The first option is to move our logic into multiple server-side pages so that we can run a different query in each. That would mean adding another parameter to each selection list’s onchange handler, representing the URL of the server-side script to call.

The other option can be as simple as adding an if-else or a switch-case statement to the server-side code. The if-else structure needs a way to determine which query to execute in order to return the appropriate values. The simplest check is to decide which SQL query to use based on the name of the select element to be populated. So, when we are performing a triple combo, we can check that the value of the strElem variable. This way, we do not need to make any changes to the onchange event handlers in the client-side code.

Dim strSql As String
If strElem = "ddlTerritory" Then
    strSql = "SELECT TerritoryDescription, " & _
             " TerritoryID" & _
             " FROM Territories" & _
             " WHERE " & strWhere & _
             " ORDER BY TerritoryDescription"
Else
    strSql = "SELECT Column1, Column2" & _
             " FROM TableName" & _
             " WHERE " & strWhere & _
             " ORDER BY Column2"
End If

With this solution, as long as the drop-down lists have unique names, you will be able to have multiple combination elements on the page without having to separate all of the logic into different server-side pages.

Refactoring

So what do you think is lacking at this point? I suspect I know what you’re thinking—generality. This is an extremely cool, jazzed-up technique for implementing double combos, but it needs a little polish to be a generalized component. We’ll get there, so hang tight. But first, let’s address something even more fundamental: encapsulation of some of the Ajax plumbing itself. The net.ContentLoader is a good start. Let’s build on this object to make our handling of AJAX even more seamless. Ideally we should be able to think of this entity as an Ajax “helper” object that does all the heavy lifting associated with Ajax processing. This will allow our component to focus on double combo–specific behaviors and reduce the amount of code required by the rest of our components as well. Our improved net.ContentLoader object should ideally encapsulate the state and behavior required to perform the following tasks:

  • Creation of the XMLHttpRequest object in a cross-browser fashion, and as an independent behavior from sending requests. This will allow callers to use the creation method independently from the rest of the object. This is useful if the caller is using another idiom, framework, or mechanism for request/response activities.
  • Provide a more convenient API for dealing with request parameters. Ideally the caller should just be able to pass state from the application and let the net.ContentLoader “helper” worry about creating querystrings.
  • Routing the response back to a component that knows how to handle it and performing appropriate error handling.

So let’s start our refactoring of net.ContentLoader, and then we’ll move on to repackaging our double combo as a component.

New and improved net.ContentLoader

Let’s start by thinking about how the constructor should be changed. Consider the following constructor:

The constructor shown here is called with four arguments. The first, component, designates the object that is using the services of this helper. The helper object will assume that component has an ajaxUpdate() method to handle responses and a handleError() method to handle error conditions. More about that later. Second, as before, url designates the URL that is invoked by this helper to asynchronously get data from the server. The method parameter designates the HTTP request method. Valid values are GET and POST. Finally, the requestParameters argument is an array of strings of the form key=value, which designate the request parameters to pass to the request. This allows the caller to specify a set of request parameters that do not change between requests. These will be appended to any additional request parameters passed into the sendRequest method discussed below. So our helper can now be constructed by a client as follows:

var str = "Eastern";
var aComp = new SomeCoolComponent(...);
var ajaxHelper = new net.ContentLoader( aComp,
                "getRefreshData.aspx", "POST",
                [ "query=" + str, "ignore_case=true" ] );

Now let’s consider the rest of the API. One thing I should mention at this point is the stylistic nature of the code sample. The methods of this object are scoped to the prototype object attached to the constructor function. This is a common technique when writing object-oriented JavaScript, as it applies the method definitions to all instances of the object. However, there are several ways of syntactically specifying this. One of my favorites (a pattern I picked up from the prototype.js library packaged within Ruby On Rails) is to create the prototype object literally, as shown here:

The thing we like about this syntactically is that it is expressed minimally. The way to read this is that the outermost open and close curly braces represent an object literal, and the content is a comma-delimited list of property-value pairs within the object. In this case our properties are methods. The property-value pairs are specified as the name of the property, followed by a colon, followed by the value of the property. In this case the values (or definitions if you prefer) are function literals. Piece of cake, huh? Just bear in mind that the methods shown from here on out are assumed to be contained within the prototype object literal as shown here. Also, note that the last property doesn’t need—indeed can’t have—a comma after it. Now let’s go back to the task at hand: refactoring the API.

The API should address the requirements that we mentioned above, so let’s take each one in turn. The first thing we need is an independent behavior to handle the creation of the XMLHttpRequest object in a cross-browser fashion. That sounds like a method. Fortunately, we’ve implemented this one a few times already. All we need to do is create it as a method of our helper, as shown in listing 6, and we’ll never have to write it again.

Listing 6: The getTransport method

There’s not much explanation required here, since we’ve covered this ground many times, but now we have a cleanly packaged method to provide a cross-browser Ajax data transport object for handling our asynchronous communications.

The second requirement we mentioned was to provide a more convenient API for dealing with request parameters. In order for it to be used across a wide variety of applications, it is almost certain that the request being sent will need run-time values as parameters. We’ve already stored some initial state that represents request parameters that are constant across requests, but we’ll also need runtime values. Let’s decide on supporting a usage such as the following code:

So given this usage requirement, sendRequest is defined as shown in listing 7.

Listing 7: The sendRequest method

This method splits the process of sending a request into four steps. Let’s look at each step of the process in detail:

The following list references the callouts in listing 7.

  1. This step takes advantage of the fact that JavaScript creates a pseudo-array named arguments that is scoped to the function. As the name suggests, arguments holds the arguments that were passed to the function. In this case the arguments are expected to be strings of the form key=value. We just copy them into a first-class array for now. Also, note that all variables created in this method are preceded by the keyword var. Although JavaScript is perfectly happy if we leave the
    var keyword off, it’s very important that we don’t. Why? Because, if we omit the var keyword, the variable is created at a global scope—visible to all the code in your JavaScript universe! This could cause unexpected interactions with other code (for example, someone names a variable with the same name in a third-party script you have included). In short, it’s a debugging nightmare waiting to happen. Do yourself a favor and get accustomed to the discipline of using locally scoped variables whenever possible.
  2. Here our method uses the getTransport method we defined in listing 6 to create an instance of an XMLHttpRequest object. Then the request is opened and its Content-Type header is initialized as in previous examples. The object reference is held in a local variable named request.
  3. This step takes care of the response-handling task. I’ll bet you’re wondering why the variable oThis was created. You’ll note that the following line—an anonymous function that responds to the onreadystatechange of our request object—references oThis. The name for what’s going on here is a closure. By virtue of the inner function referencing the local variable, an implicit execution context or scope is created to allow the reference to be maintained after the enclosing function exits. (See appendix B for more on closures.) This lets us implement handling of the Ajax response by calling a first-class method on our ajaxHelper object.
  4. Finally, we send the Ajax request. Note that the array we created in step 1 is passed to a method named queryString that converts it to a single string. That string becomes the body of the Ajax request. The queryString method isn’t really part of the public contract we discussed earlier, but it’s a helper method that keeps the code clean and readable. Let’s take a look at it in listing 8.

Listing 8: The queryString method

This method takes the request parameters that our net.ContentLoader was constructed with, along with the additional runtime parameters that were passed into the sendRequest method, and places them into a single array. It then iterates over the array and converts it into a querystring. An example of what this achieves is shown here:

var helper = new net.ContentLoader( someObj, someUrl,
                                    "POST", ["a=one", "b=two"] );
var str = ajaxHelper.queryString( ["c=three", "d=four"] );
str => "a=one&b=two&c=three&d=four"

The last thing we need to do to have a fully functional helper object is to collaborate with a component to handle the response that comes back from Ajax. If you’ve been paying attention, you probably already know what this method will be named. Our sendRequest method already specified how it will handle the response from the onreadystatechange property of the request:

request.onreadystatechange = function(){
   oThis.handleAjaxResponse(request)
}

That’s right, kids; all we need to do is implement a method named handleAjaxResponse. Listing 9 contains the implementation.

Listing 9: The Ajax response handler methods

All the method does is check for the appropriate readyState of 4 (indicating completion) and notifies the this.component that the response is available. But we’re not quite finished yet. The other requirement we said we would address is to handle errors appropriately. But what is appropriate? The point is, we don’t know what’s appropriate. How to handle the error is a decision that should be deferred to another entity. Therefore we assume that our client, this.component, has a handleError method that takes appropriate action when the Ajax response comes back in a way we didn’t expect. The component may in turn delegate the decision to yet another entity, but that’s beyond the scope of what we care about as a helper object. We’ve provided the mechanism; we’ll let another entity provide the semantics. As mentioned earlier, we’re assuming that this.component has an ajaxUpdate and a handleError method. This is an implicit contract that we’ve created, since JavaScript isn’t a strongly typed language that can enforce such constraints.

Congratulations! You’ve morphed net.ContentLoader into a flexible helper to do all the Ajax heavy lifting for your Ajax-enabled DHTML components. And if you have a DHTML component that’s not yet Ajax-enabled, now it’ll be easier! Speaking of which, we have a double-combo component to write.

Creating a double-combo component

We’ve laid some groundwork with our net.ContentLoader to make our task here much easier, so let’s get started. Let’s assume that our assignment as a rock-star status developer is to create a double-combo script that can be reused in many contexts across an application, or many applications for that matter. We need to consider several features in order to meet this requirement:

  • Let’s assume that we may not be able or want to directly change the HTML markup for the select boxes. This could be the case if we are not responsible for producing the markup. Perhaps the select is generated by a JSP or other server-language-specific tag. Or perhaps a designer is writing the HTML, and we want to keep it as pristine as possible to avoid major reworks caused by a round or two of page redesigns.
  • We want a combo script that is able to use different URLs and request parameters to return the option data. We also want the design to accommodate further customization.
  • We want to be able to apply this double-combo behavior potentially across multiple sets of select tags on the same page, also potentially setting up triple or quadruple combos, as discussed earlier.

Starting from the perspective of our first task, keeping the HTML markup as pristine as possible, let’s assume the markup shown in listing 10 is representative of the HTML on which we will be operating.

Listing 10: Double-combo HTML markup listing

<html>
<body>

<form name="Form1">
   <select id="region" name="region" >
      <options...>
   </select>
   <select id="territory" name="territory" />
</form>
</body>
</html>

What we need is a DoubleCombo component that we can attach to our document to perform all of the double-combo magic. So let’s work backwards and consider what we would want our markup to look like; then we’ll figure out how to implement it. Let’s change the markup to look something like listing 11.

Listing 11: Double-combo HTML modified markup listing

The markup has now changed in the following ways:

  • A function has been created that injects all desired component behaviors into our document.
  • An onload handler has been added to the body element that calls this function.

Note that nothing within the body section of the page has been modified. As stated earlier, this is a good thing. We’ve already satisfied our first requirement. But, looking at our injectComponentBehaviors() function, it’s apparent that we have some more work to do. Namely, we need to create a JavaScript object named DoubleCombo that, when constructed, provides all the behaviors we need to support double-combo functionality.

DoubleCombo component logic

Let’s start by looking more closely at the semantics of our component creation. Our injectComponentBehaviors() function creates a DoubleCombo object by calling its constructor. The constructor is defined in listing 12.

Listing 12: DoubleCombo constructor

This should be a familiar construct at this point; our constructor function initializes the state of our DoubleCombo. A description of the arguments that should be passed to the constructor is shown in table 2.

Table 2: Description of arguments

Argument Description
masterId The ID of the element in the markup corresponding to the master select element. The selection made in this element determines the values displayed by a second select element.
slaveId The ID of the element in the markup corresponding to the slave select element. This is the element whose values will be changed when the user makes a choice from the master select.
options A generic object that provides other data required by the double combo.

Consider the nature of the state maintained by the DoubleCombo object—particularly the URL and options. These two pieces of state satisfy the second functional requirement mentioned earlier. That is, our component can accommodate any URL for data retrieval and is customizable via the options parameter. Currently the only thing we assume we’ll find within the options object is a requestParameters property. But, because the options parameter is just a general object, we could set any property on it needed to facilitate further customizations down the road. The most obvious kinds of properties we could place in our options object are such things as CSS class stylings and the like. However, the style and function of the double combo are fairly independent concepts, so we’ll leave the styling to the page designer.

To many of you, we’re sure, the more interesting part of the constructor comes in the last two lines. Let’s look at each in turn:

this.ajaxHelper = new net.ContentLoader( this, url, "POST",
                          options.requestParameters || [] );

Obviously, we know that our component requires Ajax capabilities. As fortune and a little planning would have it, we already have an object to perform the lion’s share of our Ajax-related work—that is, the net.ContentLoader we cleverly refactored earlier. The DoubleCombo simply passes itself (via this) as the component parameter to the ContentLoader helper. The url parameter is also passed through to the helper as the target URL of Ajax requests, and the HTTP request method is specified with the string "POST". Finally, the requestParameters property of the options object, or an empty array if none was defined, is passed as the “constant” parameter array to send with every Ajax request. Also recall that because we passed this as a component argument, the DoubleCombo object is obligated to implement the implied contract with the net.ContentLoader object we discussed earlier. That is, we must implement an ajaxUpdate() and a handleError() method. We’ll get to that in a bit, but first let’s look at the last line of our constructor:

this.initializeBehavior();

Finally our constructor is doing something that looks like behavior. Yes, the moment we’ve all been waiting for: the behavior implementation. Everything we’ll do from here on out is directly related to providing double-combo functionality. So without further ado, let’s take a look at this method along with all the other DoubleCombo methods that will be required. Thanks to all of the infrastructure we’ve put in place, our task is far from daunting at this point. Keep in mind that all the methods that appear throughout the rest of the example are assumed to be embedded within a prototype literal object, exactly as we did for the net.ContentLoader implementation.

DoubleCombo.prototype = {
   // all of the methods….
};

So, let’s peek under the hood. First, the initializeBehavior() method is shown here:

initializeBehavior: function() {
   var oThis = this;
   this.master.onchange =
      function() { oThis.masterComboChanged(); };
},

Short and sweet. This method puts an onchange event handler on the master select element (formerly done in the HTML markup itself). When triggered, the event handler invokes another method on our object, masterComboChanged():

masterComboChanged: function() {
   var query = this.master.options[
               this.master.selectedIndex].value;
   this.ajaxHelper.sendRequest( 'q=' + query );
},

Wow, also short and sweet. All this method has to do is create a request parameter and send our Ajax request. Since the Ajax-specific work has been factored out into another object, this is a single line of code. Recall that sendRequest() will create and send an XMLHttpRequest, then route the response back to our ajaxUpdate() method. So let’s write that:

This method takes the response XML from the request object and passes it to a method named createOptions(), which creates our slave select‘s option elements. The method then simply clears and repopulates the slave select element. The createOptions() method, although not part of any public contract, is a helper method that makes the code cleaner and more readable. Its implementation, along with another helper method, getElementContent(), is shown in listing 13.

Listing 13: Combo population methods.

createOptions: function(ajaxResponse) {
   var newOptions = [];
   var entries = ajaxResponse.getElementsByTagName('entry');
   for ( var i = 0 ; i < entries.length ; i++ ) {
      var text = this.getElementContent(entries[i],
                                        'optionText');
      var value = this.getElementContent(entries[i],
                                         'optionValue');
      newOptions.push( new Option( text, value ) );
   }
return newOptions;
},

getElementContent: function(element,tagName) {
   var childElement = element.getElementsByTagName(tagName)[0];
   return (childElement.text != undefined) ? childElement.text :
      childElement.textContent;
},

These methods perform the hard work of actually fetching values from the XML response document, and creating options objects from them. To recap, the XML structure of the response is as follows:

<?xml version="1.0" ?>
<selectChoice>
   ...
   <entry>
      <optionText>Select A Territory</optionText>
      <optionValue>-1</optionValue>
   </entry>
   <entry>
      <optionText>TerritoryDescription</optionText>
      <optionValue>TerritoryID</optionValue>
   </entry>
</selectChoice>

The createOptions() method iterates over each entry element in the XML and gets the text out of the optionText and optionValue elements via the getElementContent() helper method. The only thing particularly noteworthy about the getElementContent() method is that it uses the IE-specific text attribute of the XML element if it exists; otherwise it uses the W3C-standardized textContent attribute.

Error handling

We’re all finished. Almost. We’ve implemented all the behaviors needed to make this component fully operational. But, dang, we said we’d handle error conditions, too. You will recall that we have to implement a handleError() method in order to play nicely with the net.ContentLoader. So let’s implement that, and then we’ll really be finished. So what’s the appropriate recovery action if an error occurs? At this point we still can’t really say. The application using our DoubleCombo component ultimately should decide. Sounds like a job for our options object—remember the one we passed to the constructor? Let’s think about that contract for a second. What if we constructed our double-combo component with code that looks something like this?

function myApplicationErrorHandler(request) {
   // Application function that knows how
   // to handle an error condition
}

var comboOptions = { requestParameters: [
                    "param1=one", "param2=two" ],
                    errorHandler: myApplicationErrorHandler };

var doubleCombo = new DoubleCombo( 'region',
                                   'territory',
                                   'DoubleComboXML.aspx',
                                   comboOptions );

In this scenario, we’ve let the application define a function called myApplicationErrorHandler(). The implementation of this method is finally where we can put application-specific logic to handle the error condition. This could be an alert. Or it could be a much less intrusive “oops” message a la GMail. The point is we’ve deferred this decision to the application that’s using our component. Again, we’ve provided the mechanism and allowed someone else to provide the semantics. So now we have to write the DoubleCombo object’s handleError() method:

handleError: function(request) {
   if ( this.options.errorHandler )
     this.options.errorHandler(request);
}

Component bliss

Congratulations are in order! We’re finally all done. We have a general component that we can construct with the IDs of any two select elements and some configuration information, and we have instant double-combo capability. And it’s just so … door slams open!

Enter pointy-haired manager, 2:45 P. M. Friday. “Johnson,” he says. “We have to support subterritories! … And we need it by Monday morning!” Dramatic pause. “Ouch!” you finally retort. Then you regain your composure and say, “I’ll make it happen, sir. Even if I have to work all weekend.” He hands you the new page design:

<form>
<select id="region"       name="region"><select>
<select id="territory"    name="territory"></select>
<select id="subTerritory" name="subTerritory"></select>
</form>

Pointy-hair retreats. You open the HTML page in Emacs, because that’s the way you roll. You go directly to the head section. The cursor blinks. You begin to type:

<script>
   function injectComponentBehaviors() {
      var opts1 = { requestParameters: "master=region" };
      var opts2 = { requestParameters: "master=territory" };

      new DoubleCombo( 'region',
                       'territory',
                       'DoubleComboXML.aspx', opts1 );
      new DoubleCombo( 'territory',
                       'subTerritory',
                       'DoubleComboXML.aspx', opts2 );
</script>

You press a key that runs a macro to nicely format your code. You save. You exclaim over your shoulder, “I’ll be working from home,” as you pass by Pointy’s office at 2:57. You plop down on the sofa and think to yourself, “Boy, I am a rock star!” Okay, already. Enough of the fantasy. Let’s tie a bow around this thing and call it a day.

Summary

The double combination select element is an efficient method to create dynamic form elements for the user. We can use JavaScript event handlers to detect changes in one select element and trigger a process to update the values in the second element. By using Ajax, we are able to avoid the long page-loading time that you would see using a JavaScript-only solution. Using Ajax, we can make a database query without the entire page being posted back to the server and disrupting the user’s interaction with the form. Ajax makes it easy for your web application to act more like a client application.

With this code, you should be able to develop more sophisticated forms without having to worry about the normal problems of posting pages back to the server. With the ability to extend this script to act on multiple combinations of selection lists, your users can drill down more precisely through several layers of options to obtain the information or products they are looking for.

Finally, we did some refactoring of the code to build ourselves an industrial-strength component to facilitate reuse and customization down the road. From our perspective, we’ve encapsulated this functionality in a reusable component and won’t ever need to write it again. From our users’ perspective, they won’t be getting that screen that says the product is not available when buying items from our online store. Everybody’s happy.

About the Authors

Dave Crane has pushed the boundaries of DHTML, and latterly Ajax, on digital TV set-top boxes, in home automation and banking and financial systems. He lives in Gloucestershire, UK.

Eric Pascarello is an ASP.NET developer and a moderator of the HTML and JavaScript forum at JavaRanch. He lives in Laurel, MD.

Darren James is the architect of the opensource Rico project. He lives in Sunnyvale, CA.

About the Book

Ajax in Action
By Dave Crane, Eric Pascarello, and Darren James

Published: October, 2005, Paperback: 680 pages
Published by Manning Publications Co.
ISBN: 1932394613
Retail price: $44.95

This material is from Chapter 9 of the book.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories