Friday, December 9, 2011

Adding more parameters to the GET request in the JQuery UI Autocomplete

Working with the JQuery UI Autocomplete in the remote datasource way, my problem begun when I needed to add more parameters when making the call by GET method. Lucky, I found this  page, but in that example the author was using a simple JSON structure:
[{"name":"name 1"},{"name":"name 2"}]

Here is the URL request


As you can see the parameter term is where we send our request. 

By another hand, isn't explained in the JQuery UI Autocomplete how the JSON should be return. 


Here is the structure
 -id
 -label
 -value

Example 
[{"id":"id 1","label":"label 1","value":"value 1"},{"id":"id 2","label":"label 2","value":"value 2"}]

So, knowing these details I made the little change.

$("#searchBox").autocomplete({ 
    source: function(req,add){
        $.getJSON("source.php?parameter1=param1&meter2=param2", req  , function(data){
            var suggestions = [];
            $.each(data,function(i,val){
                suggestions.push(val);
            });
            add(suggestions);
        });
    },
    select: function(event,ui){
        alert("The ID is "+ui.item.id+" the value is "+ui.item.value);
      },
    change: function(){
     $('#searchBox').val('');
    }
  });


Here an example with the parameter clientid added
Here is how must be the structure of the returned JSON

No comments:

Post a Comment