Home » Tutorials Advanced Tutorial

Creating an Autosuggest Textbox with JavaScript, Part 3 - Page 3

3.3/5.0 (10 votes total)
Rate:

Nicholas C. Zakas
February 13, 2006


Nicholas C. Zakas
Nicholas C. Zakas is a professional Web designer who specializes in user interface design for Web applications using JavaScript, Dynamic HTML, CSS, XML, and XSLT.


http://www.nczonline.net
Nicholas C. Zakas has written 12 tutorials for JavaScriptSearch.
View all tutorials by Nicholas C. Zakas...

Creating the Suggestion Provider

For this remote functionality, you'll need to create a new suggestion provider. The only property necessary is an instance of XMLHttpRequest to facilitate the client-server communication. In Internet Explorer, you'll need to use the ActiveX version, in other browsers that support it (such as Mozilla, Safari, and Opera), you'll use the XMLHttpRequest object itself:

function RemoteStateSuggestions() {

    if (typeof XMLHttpRequest != "undefined") {
        this.http = new XMLHttpRequest();
    } else if (typeof ActiveXObject != "undefined") {
        this.http = new ActiveXObject("MSXML2.XmlHttp");
    } else {
        alert("No XMLHttpRequest object available. This functionality will not work.");
    }

}

The reference to the XMLHttpRequest object is stored in the http property. There's no need to create new instances of this object every time there's a request. It's just easier to reuse the same object.

The requestSuggestions() method is where the real magic happens. Here's the code (explanation to follow):

RemoteStateSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl,
bTypeAhead) {

    var oHttp = this.http;

    if (oHttp.readyState != 0) {
        oHttp.abort();
    }

    var sURL = "suggestions.php?userInput=" + encodeURIComponent(oAutoSuggestControl.textbox.value);

    oHttp.open("get", sURL , true);
    oHttp.onreadystatechange = function () {
        if (oHttp.readyState == 4) {
            var aSuggestions = eval(oHttp.responseText);
            oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
        }
    };
    oHttp.send(null);

};

The first thing this method does is create a variable called oHttp to store the reference to the XMLHttpRequest object. This is done for convenience and also to work around an issue with Microsoft's implementation.

Next, you must check to see if a request is already in progress. For various reasons, one request may not have completed before the next one needs to be sent out. If there is no active request, then the readyState property is set to 0, so this is how you can check. When readyState isn't zero, you need to abort the current request before a new one can be sent out. This is done by calling the abort() method. Now you can safely begin a new request.

Before sending the request, you need to build the URL. In this case, you simply need to add the contents of the textbox to the "suggestions.php?userInput=" string. Make sure to encode this value using encodeURIComponent(), just in case there are special characters that are invalid in URLs (such as spaces or quotation marks). With the URL created, it's time to begin the request.

The next line uses the open() method to open a GET request to the URL. The last argument specifies this as an asynchronous request, meaning that the code won't wait for the request to return something. Instead, you need to use the onreadystatechange event handler to check for a response. Inside of this event handler, you need to check for when readyState is equal to 4, meaning that the request has completed. When that happens, evaluate the responseText (which contains the array literal) into an array, aSuggestions and pass it back to the autosuggest control.

After the event handler is defined, the request must be sent using the send() method. An argument is required, so you can just pass in null. And that's it!

Example

To use the new code, just set up a page and include the appropriate files:

<html>
    <head>
        <title>Autosuggest Example 2</title>
        <script type="text/javascript" src="autosuggest2.js"></script>
        <script type="text/javascript" src="remotesuggestions.js"></script>
        <link rel="stylesheet" type="text/css" src="autosuggest.css" />

        <script type="text/javascript">
            window.onload = function () {
                var oTextbox = new AutoSuggestControl(document.getElementById("txt1"), new RemoteStateSuggestions());
            }
        </script>
    </head>
    <body>
        <p><input type="text" id="txt1" /></p>
    </body>
</html>

Note that the suggestion provider must be updated to be RemoteStateSuggestions.You can view the example here (it should work in Internet Explorer 5.5+ and Mozilla 1.0+, including Firefox) or download it along with the previous example.

This example relies on a PHP server, so you won't be able to run it locally. If you have a Web host that provides PHP support, you can upload the example files to try them out.

Conclusion

Over the past three articles, you've learned how to implement an autosuggest control that can go back to the server for its suggestions. Note that what has been presented here might not match your specific needs, but you should have enough background to modify the examples as necessary. In most cases, you'll be able to simply define a new suggestion provider to alter the behavior of the autosuggest control. Happy coding!


Add commentAdd comment (Comments: 0)  

Advertisement

Partners

Related Resources

Other Resources

arrow