jQuery Cool Auto-Suggest



Classic Style

The classic style of auto-suggest. It takes just one parameter, the URL to retrieve the data.

Public figure name :

The code :

$("#text1").coolautosuggest({
  url:"data.php?chars="
});

Using ID Field

The auto-suggest can also return an ID. You just need to prepare the input element for storing it and then pass one additional parameter, idField.

Public figure name : ID :

The code :

$("#text2").coolautosuggest({
  url:"data.php?chars=",
  idField:$("#text2_id")
});

Image Thumbnail And Additional Description

The auto-suggest can also display image thumbnail and additional description. You have to pass two additional parameters, showThumbnail, and showDescription and then set their value to true.

Public figure name :

The code :

$("#text3").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true
});

Note :

Image thumbnail's width and height can be set from the CSS file.
For a better appearance, I recommend that all images must have the same width and height.


Other Options

These are the other usefull parameters which you can use. Here they are.

  • width. Basically, the width will be automatically adjusted to textfield's width. By using this parameter, you can customize the auto-suggest width to suit your need.
  • minChars. By default, the auto-suggest will appear if you type the first letter. You can set the number characters typed to trigger the auto-suggest to appear by using this parameter.
  • submitOnSelect. By setting this parameter value to true, the form will be submitted once you click one of the item in the auto-suggest list.
Public figure name : ID :

The code :

$("#text4").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true,
  idField:$("#text4_id"),
  width:300,
  minChars:2,
  submitOnSelect:true
});

Callback Function

For this new version, you can use one callback function which can be used via onSelected parameter. This callback function will be executed when you made a selection on one item (by clicking it or pressing 'Enter'). By using this callback feature you can retrieve the selected object to be used later in your code.

Public figure name :
ID :
Profession :
Picture :

Sample code :

$("#text5").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true,
  onSelected:function(result){
    // Check if the result is not null
    if(result!=null){
      $("#text5_id").val(result.id); // Get the ID field
      $("#text5_profession").val(result.description); // Get the description
      $("#picture").html('<img src="' + result.thumbnail + '" alt="" />'); // Get the picture thumbnail
    }
    else{
      $("#text5_id").val(""); // Empty the ID field
      $("#text5_profession").val(""); // Empty the description
      $("#picture").html(''); // Empty the picture thumbnail
    }
  }
});

Note :

This callback feature can also be used as the alternative to get the ID of the selected item and also submit the form after you made the selection.


Additional Dynamic Query String

We can pass additional dynamic query string to the request URL. For the example, we may need to filter the autocomplete list based on the previously selected profession.

Profession :
Public figure name :
ID :
Picture :

Sample code :

$("#text6").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true,
  additionalFields:{
    "&profession=" : $("select[name=profession]") // We can use more than one criteria if needed.
  },
  onSelected:function(result){
    // Check if the result is not null
    if(result!=null){
      $("#text6_id").val(result.id); // Get the ID field
      $("#picture").html('<img src="' + result.thumbnail + '" alt="" />'); // Get the picture thumbnail
    }
    else{
      $("#text6_id").val(""); // Empty the ID field
      $("#picture").html(''); // Empty the picture thumbnail
    }
  }
});

Note :

The additionalFields should be in key value pair. The string we used for the key is flexible, it can be "&profession=" or "/profession/" or anything depend on our needs.


Error Callback

We can also use custom error callback function to display custom error message when there is something wrong on the autocomplete process.

Public figure name :

Sample code :

$("#text7").coolautosuggest({
  url:"notfound.php?chars=", // We point to wrong URL to raise error.
  onError:function() {
    alert("Hey, it seems something error has happened.");
  }
});

Server Side Script

For the server side script which populate the auto-suggest data, you can use the code below. Please remember that the data is transferred in JSON format.

<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-type: application/json");

$host="localhost";
$username="root";
$password="";
$database="test";

$con=mysqli_connect($host,$username,$password,$database);

$arr=array();

$profession = "";
if (isset($_GET['profession'])) {
    $profession = " AND description = '" . mysqli_real_escape_string($con, $_GET['profession']) . "' ";
}

$result=mysqli_query($con,"SELECT * FROM people WHERE name LIKE '%".mysqli_real_escape_string($con,$_GET['chars'])."%' " . $profession . " ORDER BY name LIMIT 0, 10");
if(mysqli_num_rows($result)>0){
    while($data=mysqli_fetch_row($result)){
        // Store data in array
        // You can add any additional fields to be used by the autosuggest callback function
        $arr[]=array(
            "id" => $data[0],
            "data" => $data[1],
            "thumbnail" => 'thumbnails/'.$data[3],
            "description" => $data[2],
            // Additional fields (if any)...
        );
    }
}

mysqli_close($con);

// Encode it with JSON format
echo json_encode($arr);

Or, you can use the PDO instead of mysqli_ like following.

<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-type: application/json");

$host="localhost";
$username="root";
$password="";
$database="test";

$db = new PDO("mysql:host=$host;dbname=$database" , $username , $password);

$arr = array();

$where = array();
$where[':name'] = '%' . $_GET['chars'] . '%';

$profession = "";
if (isset($_GET['profession'])) {
    $profession = " AND description = :description ";
    $where[':description'] = $_GET['profession'];
}

$sql = "SELECT * FROM people WHERE name LIKE :name " . $profession . " ORDER BY name LIMIT 0, 10";

$query = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$query->execute($where);

$result = $query->fetchAll();
if ($query->rowCount() > 0) {
    foreach ($result as $data) {
        // Store data in array
        // You can add any additional fields to be used by the autosuggest callback function
        $arr[]=array(
            "id" => $data['id'],
            "data" => $data['name'],
            "thumbnail" => 'thumbnails/'.$data['photo'],
            "description" => $data['description'],
            // Additional fields (if any)...
        );
    }
}

// Close connection.
$db = null;

// Encode it with JSON format
echo json_encode($arr);