LanguagesJavaScriptCreating a Double-Combo Linked List with Ajax

Creating a Double-Combo Linked List with Ajax

If you have ever shopped for a new shirt online, you may have run into the following problem. You pick the shirt size from one drop-down list, and from the next drop-down list you select the color. You then submit the form and get the message in giant red letters: “Sorry, that item is not in stock.” Frustration sets in as you have to hit the back button or click a link to select a new color.

With Ajax we can eliminate that frustration. We can link the selection lists together, and when our user selects the size option from the first list, all of the available colors for that shirt can be populated to the second list directly from the database—without the user having to refresh the whole page. People have been linking two or more selection lists together to perform this action with either hard-coded JavaScript arrays or server-side postbacks, but now with Ajax we have a better way.

A double-combo script

In a double-combination linked list, the contents of one selection list are dependent on another selection list’s selected option. When the user selects a value from the first list, all of the items in the second list update dynamically. This functionality is typically called a double-combo script.

There are two traditional solutions for implementing the dynamic filling of the second selection list: one is implemented on the client and the other on the server. Let’s review how they work in order to understand the concepts behind these strategies and the concerns developers have with them.

Limitations of a client-side solution

The first option a developer traditionally had was to use a client-side-only solution. It uses a JavaScript method in which the values for the selection lists are hard-coded into JavaScript arrays on the web page. As soon as you pick a shirt size, the script seamlessly fills in the next selection list by selecting the values from the array. This solution is shown in figure 1.

One problem with this client-side method is that, because it does not communicate with the server, it lacks the ability to grab up-to-date data at the moment the user’s first selection is made. Another problem is the initial page-loading time, which scales poorly as the number of possible options in the two lists grows. Imagine a store with a thousand items; values for each item would have to be placed in a JavaScript array. Since the code to represent this array would be part of the page’s content, the user might face a long wait when first loading the page. There is no efficient way to transmit all of that information to the client up-front.

Figure 1: The client-side solution

On the other hand, the JavaScript method has one benefit: after the initial load time, it is fast. There is no major lag between selecting an option from the first selection list and the second list being populated. So this method is only usable if you have just a few double-combination options that will not impact the page-loading time significantly.

Limitations of a server-side solution

The next traditional solution is the submission of a form back to the server, which is known as a page postback. In this method, the onchange event handler in the first selection list triggers a postback to the server, via the submit() method of the form’s JavaScript representation. This submits the form to the server, transmitting the user’s choice from the first select element. The server, in turn, queries a database based on the value that the user selected, and dynamically fills in the new values for the second list, as it re-renders the page. You can see the process of the server-side method in figure 2.

Figure 2: The client-side architecture

A drawback to the server-side method is the number of round-trips to the server; each time the page is reloaded, there is a time delay, since the entire page has to re-render. Figure 2 shows all of the extra processing required. Additional server-side code is also needed to reselect the user’s choice on the first select element of the re-rendered page. Moreover, if the page was scrolled to a particular spot before the form was submitted, the user will have to scroll back to that location after the page reloads.

Ajax-based solution

We can avoid the problems of the JavaScript and server-side solutions by using Ajax to transfer data to the server and obtain the desired information for the second selection list. This allows the database to be queried and the form element to be filled in dynamically with only a slight pause. Compared with the JavaScript method, we are saving the extra page-loading time that was required to load all of the available options into the arrays. Compared with the server-side postback solution, we are eliminating the need to post the entire page back to the server; instead, we are passing only the information necessary. The page is not reloaded, so you do not have to worry about the scroll position of the page or what option was selected in the first drop-down field. The initial page loading time is also shortened since the JavaScript arrays do not have to be included in the page.

This example will involve two selection lists. The first selection list contains the sales regions for a company. The second selection list displays the related territories for the selected region, as shown in figure 3.

When the user selects a region from the first selection list, the client sends a request to the server containing only the necessary information to identify both the selected region, and the form control to populate with the list of territories. The server queries the database and returns an XML document containing the names of the territories in the selected region, and also the names of the form and the control that the client needs to update. Let’s see how this works.

The first step in building the Ajax solution takes place on the client.

Figure 3: The Ajax solution

The client-side architecture

The client-side architecture is foreign territory to most developers who normally write server-side code. In this case, it is not that scary since we need to take only a few steps to get the options into our second selection list. If you have implemented the JavaScript or server-side solutions for a double combo before, then you have already have experience with part of the processes involved.

As you can see in figure 4, this application’s client-side interaction does not require many steps. The first step is to build the initial form. The user then selects an item from the form’s first select. This initiates the second step of the client-side architecture, which is to create an XMLHttpRequest object to interact with the server. This transmits the user’s selection to the server, along with the names of the form and the control that will be updated when the server’s response is received. The third part requires us to add the contents of the server’s XML response to the second select element. JavaScript’s XML DOM methods are used to parse the XML response.

Figure 4: Client-side architecture, showing the Ajax interaction

Let’s go over the first two steps, which happen before the Ajax request is sent to the server. We’ll explain the third step (the DOM interaction with the server’s XML response document) in more detail later, since we need to talk about the server before we can implement the client-side architecture completely.

Designing the form

The form in this example involves two select elements. The first select element will initially contain values, while the second selection list will be empty. Figure 5 shows the form.

Figure 5: Available options in the first select element

The first form element can be filled in three separate ways initially, as shown in table 1.

Table 1: Three ways to populate a form element

Method Advantages Disadvantages
Hard-code the values into the select element. No server-side processing. Options cannot be dynamic.
Fill in the values by using a server-side script. Options can be dynamic and pulled from the database. Requires extra processing on the server.
Use Ajax to fill in the values; this method posts back to the server to retrieve the values. Can be linked to other values on the page. Requires extra processing on the server.

The first method is to hard-code the values into the select element. This method is good when you have a few options that are not going to change. The second method is to fill in the values by using a server-side script. This approach fills in the options as the page is rendered, which allows them to be pulled from a database or XML file. The third method is to use Ajax to fill in the values; this method posts back to the server to retrieve the values but does not re-render the entire page.

In this example, we are hard-coding the values into the selection list since there are only four options and they are not dynamic. The best solution for dynamically loading values into the first selection list is to use a server-side script that fills the list as the page is loaded. Ajax should not be used to populate the first selection list unless its contents depend on other values the user selects on the form.

The first selection list needs to have an onchange event handler added to its select element, as shown in listing 1. This event handler calls the JavaScript function FillTerritory(), which initiates the process of filling the second selection list by sending a request to the server.

Listing 1: The double-combo form

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

The code in listing 1 creates a form that initiates the FillTerritory() process when an item is chosen in the first selection list. We pass two element object references to the FillTerritory() function. The first is the selection list object that the event handler is attached to, and the second is the selection list that is to be filled in. The next step for us is to develop the client-side code for FillTerritory(), which submits our request to the server.

Designing the client/server interactions

The FillTerritory() function’s main purpose is to gather the information that is needed to send a request to the server. This information includes the selected option from the first list, the name of the form, and the name of the second selection list. With this information we can use the Ajax functions in our JavaScript library to send a request to the server. The first thing we need to do is add our Ajax functionality. The code needed to link to the external JavaScript file, net.js, which defines the ContentLoader object, is trivial. Just add this between the head tags of your HTML document:

<script type="text/javascript" src="net.js"></script>

The ContentLoader object does all of the work of determining how to send a request to the server, hiding any browser-specific code behind an easy-to-use wrapper object. It allows us to send and retrieve the data from the server without refreshing the page.

With the Ajax functionality added, we are able to build the function FillTerritory(), shown in listing 2, which we also add between the head tags of our document.

Listing 2: The function FillTerritory() initializes the Ajax request.

The FillTerritory() function accepts two parameters, passed in this case from the onchange event handler on the first selection list. These are references to the first and second select elements.

The following list references the callouts in listing 2.

  1. We access the value that the user selected in the first list.
  2. We set the URL of our target server-side script.
  3. We then build the parameters to be sent to the server by creating a string that has the same type of syntax as a querystring, using an ampersand to separate each name-value pair. For this example we are sending the value representing the selected region as q, the name of the form as f, and the name of the second select as e. The server-side code will use the selected region value to query the database, and it will send the names of the form and the select element back to the client in its XML response document. The client will use that information to determine which form and control to update. Once the parameter string is built, the only thing left is to initiate the Ajax process.
  4. To start the process, we call the ContentLoader() constructor, and pass in the target URL, the function to be called when the server’s response is received, the error-handler function, the HTTP method to use, and the parameters to be sent. In this case, the FillDropDown() function will be called when the data is returned from the server, we will rely on ContentLoader’s default error-handler function, and we are using a POST request.

At this point, the ContentLoader will wait for the server to return an XML document. The client-side code continues in section 4, but first, the server has some work to do.

Implementing the server: VB .NET

The server-side code needs to retrieve the territories belonging to the user’s selected region from the database, and return them to the client in an XML document. The result set from the SQL query is used to create an XML document that is returned to the client side. Figure 6 shows the flow of the server-side process.

The server-side code is invoked by the request sent from the client-side ContentLoader object. The server-side code first retrieves the value of the request parameter q, representing the selected region. The value of q is used to create a dynamic SQL query statement, which is run against the database to find the text/value pairs for the second drop-down list. The data that is returned by the database query is then formatted as XML and returned to the client. Before we write the code to do this, we need to define the basic XML document structure.

Figure 6: Server-side process flow diagram

Defining the XML response format

We need to create a simple XML document to return the results of our database query to the client. It will contain the options to populate the second selection list. A pair of elements is needed to represent each option, one to contain the option text, and one to contain the option value.

The XML document in our example has a root element named selectChoice, containing a single element named selectElement, followed by one or more entry elements. selectElement contains the names of the HTML form and selection list that the results will populate on the client. Each entry element has two child elements, optionText and optionValue, which hold values representing each territory’s description and ID. Listing 3 shows this structure.

Listing 3: Example of the XML response format.

<?xml version="1.0" ?>
<selectChoice>
   <selectElement>
      <formName>Form1</formName>
      <formElem>ddlTerritory</formElem>
   </selectElement>
   <entry>
      <optionText>Select A Territory</optionText>
      <optionValue>-1</optionValue>
   </entry>
   <entry>
      <optionText>TerritoryDescription</optionText>
      <optionValue>TerritoryID</optionValue>
   </entry>
</selectChoice>

Notice in the example XML document in listing 3 that there is an entry containing the option text “Select A Territory”. This is the first option shown in the selection list, prompting the user to choose a value. The server-side code includes this value at the start of every response document, before the dynamic options are obtained from the database.

Now that we have our response document defined, we can develop the code that dynamically creates the XML and returns it to the client.

Writing the server-side code

The VB .NET server-side code is straightforward. We perform a query on a database, which returns a record set. We then loop through the record set to create our XML document and send the XML back to the client. If we do not find any records, then we do not create any entry elements, also omitting the static “Select A Territory” option. As you can see in listing 4, the server-side code is not very complicated. It simply contains statements to retrieve the form values posted to the server, set the content type, perform a search, and output the XML document.

This example uses the Northwind sample database from Microsoft’s SQL Server.

Listing 4: DoubleComboXML.aspx.vb: Server-side creation of the XML response

The following list references the callouts in listing 4.

  1. Setting the page’s content type to text/xml ensures that the XMLHttpRequest will parse the server response correctly on the client.
  2. We obtain the value of the selected region, the HTML form name, and the element name from the request parameters received from the client. For added safety, we could add a check here to make sure that these values are not null. If the check does not find a value for each, the script could return an error response. We should also add checks for SQL injection before the application enters a production environment. This would ensure that the database is protected from malicious requests sent by attackers.
  3. Having obtained the selected region’s value, the next step is to generate a SQL string so we can retrieve the corresponding territories from the database. The two columns we are interested in are TerritoryDescription and TerritoryID, from the database table Territories. We insert the region value into the SQL statement’s WHERE clause. To ensure that the results appear in alphabetical order in our selection list, we also set the SQL ORDER BY clause to TerritoryDescription.
  4. Next, we must execute the SQL statement. In this case, we call the function FillDataTable() to create a connection to the database server, perform the query, and return the results in a data table.
  5. Now that we have obtained the result of the SQL query, we need to create the first part of the XML document, which was discussed in listing 2. We begin the document and add the selectElement, containing the values of formName and formElem obtained from the request parameters.
  6. A check is needed to verify if any results were returned by the SQL query.
  7. If there are results, we add the preliminary “Select A Territory” option to the XML.
  8. Next we loop through the results represented in the DataTable, populating the value of the TerritoryDescription column into the optionText tag and the value of the TerritoryID column into the optionValue tag. By nesting each description/ID pair inside an entry tag, we provide an easier means to loop through the values on the client, with JavaScript’s XML DOM methods.
  9. After we finish populating our results into the XML document, we need to close the root selectChoice element and write the response to the output page j . The XML response document is returned to the client, and the ContentLoader object is notified that the server-side process is complete. The ContentLoader calls the function FillDropDown() on the client, which will process the XML that we just created.

Let’s recap what we’ve done on the server. We have taken the value from a selected item in a selection list and have run a query against a database without posting back the entire page to the server. We have then generated an XML document and returned it to the client. The next step in the process takes us back to the client side, where we must now convert the XML elements into options for our second selection list.

Presenting the results

We now have the results of our database query in an XML document, and we are going to navigate through its elements using JavaScript’s DOM API. We can easily jump to a particular element in the document using a function called getElementsByTagName(). This function uses the element’s name to look it up in the DOM, somewhat like the alphabetical tabs that stick out in an old-fashioned Rolodex. Since many elements in an XML document can have the same name, getElementsByTagName() actually returns an array of elements, in the order that they appear in the document.

Navigating the XML document

Now we will finish the client-side script that adds the options to the selection list. The names of the form and the selection element that we are going to populate are specified in the XML document along with all of the available options for the list. We need to traverse the document’s elements in order to locate the options and insert them into our select element.

Once the ContentLoader receives the XML document from the server, it will call the FillDropDown() function that appears in listing 2. In FillDropDown(), we navigate the entry elements of the XML document, and create a new Option object for each. These Option objects represent the text and value pairs that will be added to the selection list. Listing 5 shows the FillDropDown() function in full.

Listing 5: Updating the page with data from the XML response

The FillDropDown() function is called by the ContentLoader once it has received and parsed the server’s XML response. The ContentLoader object is accessible within FillDropDown() through the this reference, and we use it to obtain the response document, responseXML.

The following list references the callouts in listing 5.

  1. Once we have a reference to the response’s documentElement, we can begin using JavaScript’s DOM functions to navigate its nodes. The first information we want to obtain is the target select list to which we will add the new options. We look up the element named selectElement using getElementsByTagName(), taking the first item from the array it returns.
  2. We can then navigate to its child nodes. The first child contains the form’s name and the second child the select list’s name.
  3. Using these two values, we reference the target selection list itself, and clear
    any existing options by setting the length of its options array to 0. Now we can add
    the new options to the list. We need to access the XML’s document entry elements,
    so we call on getElementsByTagName() once again.
  4. This time we need to loop through the array of elements it returns, and obtain the text and value pairs from each. The first child node of each entry is the option text that is to be displayed to the user, and the second child node is the value. Once these two values are obtained, we create a new Option object, passing the option text as the first constructor parameter and the option value as the second. The new option is then added to the target select element, and the process is repeated until all the new options have been added. The method signature for select.add() varies between browsers, so we use a try...catch statement to find one that works.

This completes the coding for our double combo box. We can now load up our HTML page, select a region, and see the second drop-down populated directly from the database.

Figure 7 shows the double-combo list in action. In this example, the Eastern region is selected from the first list, and the corresponding territories are retrieved from the database and displayed in the second list. The Southern region is then selected from the first list, and its corresponding territories fill in the second list.

Figure 7: The double-combo list in action

As you can see in figure 7, we still have one job left: changing the selection list’s appearance to make it more appealing. The second selection list’s size expands as it is populated with options. We can fix this shift in size by applying a Cascading Style Sheet (CSS) rule to the element.

Applying Cascading Style Sheets

Cascading Style Sheets allow for changes in the visual properties of the selection element. We can change the font color, the font family, the width of the element, and so on. In figure 7 we saw that our second select element is initially only a few pixels wide since it contains no options. When the Eastern region is chosen from the first selection list, our second select element expands. This change of size is visually jarring and creates an unpleasant user experience.

The way to fix this issue is to set a width for the selection list:

<select name="ddlTerritory" style="width:200px"></select>

However, there may still be a problem if one of the displayed values is longer than the width we set. In Firefox, when the element is in focus the options under the drop-down list expand to display their entire text. However, in Microsoft Internet Explorer, the text is chopped off and is not visible to the user, as shown in figure 8.

Figure 8: Cross-browser differences in how a select element is rendered

To avoid the problem with Internet Explorer, we need to set the width of the selection list to the width of the longest option. Most of the time the only way to determine the number of pixels required to show the content is by trial and error.

Some developers use browser-specific hacks in their CSS only to set the width wider for IE:

style="width:100px;_width:250px"

Internet Explorer recognizes the width with the underscore, while other browsers ignore it. Therefore, IE’s selection box will be 250 pixels wide, while the other browsers’ selection width will be 100 pixels wide. However, it’s inadvisable to rely on browser bugs such as this one, as they may be fixed in a future version of the browser and break the way your page is displayed.

Our next article, to be published on January 18th will look at ways to add more advanced features to our double-combo script.

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.

Latest Posts

Related Stories