Book Image

PHP Ajax Cookbook

Book Image

PHP Ajax Cookbook

Overview of this book

Table of Contents (16 chapters)
PHP Ajax Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Creating an autosuggest control


This recipe will show us how to create an autosuggest control. This functionality is very useful when we need to search within huge amounts of data. The basic functionality is to display the list of suggested data based on text in the input box.

Getting ready

We can start with the dummy PHP page that will serve as a data source. When we call this script with the GET method and the variable string, it will return the list of records (names) that include the selected string:

<?php
$string = $_GET["string"];

$arr = array(
  "Adam",
  "Eva",
  "Milan",
  "Rajesh",
  "Roshan",
  // ...
  "Michael",
  "Romeo"
);

function filter($var){
  global $string;
  if(!empty($string))
    return strstr($var,$string);
}

$filteredArray = array_filter($arr, "filter");

$result = "";
foreach ($filteredArray as $key => $value){
  $row = "<li>".str_replace($string, 
    "<strong>".$string."</strong>", $value)."</li>";
  $result .= $row;
}

echo $result...