spacer

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

home / programming / javascript / ncz / column3 / 1 To page 1current pageTo page 3
[previous][next]

Senior Consultant/Information Security - permanent position (TX)
Next Step Systems
US-TX-Irving

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 Server-Side Logic

Whenever you deal with client-server communication using JavaScript, you need to determine the best way to facilitate that interaction. What should your JavaScript code expect to receive back from the server? HTML? XML? Plain text? The answer may surprise you: JavaScript. Yes, the fastest and easiest thing for JavaScript to understand from the server is JavaScript code that can be passed into the eval() function. More specifically, I prefer to use the JSON syntax first described by Douglas Crockford. This simple syntax uses array and object literals to represent data instead of using more verbose XML. For the purposes of this article, this means that what you should return from the server must look like this:

["suggestion1", "suggestion2", "suggestion3"]

This would then allow the client-side JavaScript to create an array of suggestions simply by doing this:

var aSuggestions = eval(sJSONFromServer);

No messy text parsing or array building needed! But how to output this from the server? You need only create a page in your favorite server-side language to output this text. Here's a simple PHP version of the case insensitive matching algorithm developed earlier in this article:

<?php
    header("Content-Type: text/plain; charset=UTF-8");

    $states = array(
        "Alabama", "Alaska", "Arizona", "Arkansas",
        "California", "Colorado", "Connecticut",
        "Delaware", "Florida", "Georgia", "Hawaii",
        "Idaho", "Illinois", "Indiana", "Iowa",
        "Kansas", "Kentucky", "Louisiana",
        "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota",
        "Mississippi", "Missouri", "Montana",
        "Nebraska", "Nevada", "New Hampshire", "New Mexico", "New York",
        "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon",
        "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
        "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
        "Washington", "West Virginia", "Wisconsin", "Wyoming"
    );

    $suggestions = array();

    if (strlen($userInput) > 0){

        $userInputLC = strtolower($userInput);

        for ($i=0; $i < count($states); $i++) {

            $stateLC = strtolower($states[$i]);

            $result = strpos($stateLC, $userInputLC);
            if ($result !== false && $result == 0) {
                array_push($suggestions, $userInput.substr($states[$i], strlen($userInput)));
            }
        }
    }
?>
[<?php
    for ($i = 0; $i < count($suggestions); $i++) {
        if ($i > 0) {
            echo ",";
        }
        echo "\"".$suggestions[$i]."\"";
    }
?>]

The first step on this page is to set the content type to text/plain, just to make sure this page doesn't trigger any special behaviors from the server or browser when it runs. Next, the algorithm is converted into PHP code, building up an array of suggestions and storing it in the $suggestions variable. The last part outputs the suggestions in an array literal.

The $userInput variable is passed in the query string of the page, like this:

http://yourhost.com/suggestions.php?userInput=mIs

This variable contains what the user has typed to match it against a list of possible suggestions.

Note that even though this page simply duplicates the functionality of the suggestion provider by matching the input to a list of arrays, you can easily change the page to run a search or query a database to come up with a list of possible suggestions as well.

home / programming / javascript / ncz / column3 / 1 To page 1current pageTo page 3
[previous][next]

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