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.
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
Figure 1: The client-side solution
Limitations of a server-side solution
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.
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
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
|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.
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 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.
- We access the value that the user selected in the first list.
- We set the URL of our target server-side script.
- 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.
- 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.
- Setting the page’s content type to text/xml ensures that the XMLHttpRequest will parse the server response correctly on the client.
- 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.
- 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.
- 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.
- 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.
- A check is needed to verify if any results were returned by the SQL query.
- If there are results, we add the preliminary “Select A Territory” option to the XML.
- 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
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.
- 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.
- 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.
- 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:
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.
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