Tuesday, August 7, 2012

Jquery UI autocomplete with Ajax / POST

Jquery UI has some great widgets, one of them is the autocomplete widget.
Default documentation will show you how to provide an array of tags as the source which to search from.
As useful as that is, we as developers mostly get our data from the server end, and this is one way send a request over ajax / post and get a list of results.

$("#search").autocomplete({
  source : function(request, response) 
  {
   $.post("/manager/Assets/ajax_adpsearch", 
   {
    term : request.term
   }, function(data) 
   {
    response(data)
   }, 'json');
  },
  select : function(event, ui) 
  {
   var selectedObj = ui.item;
   console.log(selectedObj.id) //selected id
  }
 });

On the server side simply construct an associative array and json encode it.

 $data = array( 
     "id" => 1, "value" => "Apple"
     ,"id" => 2, "value" => "Mango"
     ,"id" => 3, "value" => "Orange"
     ,"id" => 4, "value" => "Green Apple"
)
json_encode($data)

Sending additional data.

Some times you want to send more than just id and value pairs. In my most recent project I had a server side function that converted a given string to a SEO friendly URL format. you can put them in to the json array and access them with the array key name
 $data = array( 
     "id" => 1, "value" => "Apple" , "data" => "Fresh"
     ,"id" => 2, "value" => "Mango" , "data" => "Rotten"
     ,"id" => 3, "value" => "Orange" , "data" => "Rotten"
     ,"id" => 4, "value" => "Green Apple" , "data" => "Fresh"
)
json_encode($data)
 select : function(event, ui) 
 {
  var selectedObj = ui.item;
  console.log(selectedObj.data) // fresh or rotten
 }





No comments: