spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / ncz / column3 / 1 To page 1To page 2current page
[previous]

Web Project Manager
Aquent
US-PA-Collegeville

Justtechjobs.com Post A Job | Post A Resume
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

Creating an Autosuggest Textbox with JavaScript, Part 3

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!

About the Author

Nicholas C. Zakas is a user interface designer for Web applications and the author of Professional JavaScript for Web Developers (Wiley Press, ISBN 0764579088). Nicholas can be contacted through his Web site, http://www.nczonline.net/, where he provides open source JavaScript libraries and tools.


home / programming / javascript / ncz / column3 / 1 To page 1To page 2current page
[previous]

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Symantec Whitepaper: Converging System and Data Protection for Complete Disaster Recovery
Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
  Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Symantec Whitepaper: Comprehensive Backup and Recovery of VMware Virtual Infrastructure
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Fixing MySQL Replication · Firewall Guide: First Steps to Securing the Enterprise · VoxOx Tames the Tumultuous Communications Tangle

Created: March 27, 2003
evised: May 30, 2005

URL: http://webreference.com/programming/javascript/ncz/column3/1