Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax Autocomplete for Jquery : How To Send Dynamic Parameters

i am using Ajax Autocomplete for Jquery ( http://www.devbridge.com/projects/autocomplete/jquery/ ) in one of my application. The Search Form looks something like this :

<form id="topsearch" method="POST" action="/searchAll"><input type="text" class="searchform" name="q" id="q" value="Country, City, Hotel or a Tourist Attraction" o    nfocus="clearInput(this);" onblur="defaultInput(this);" />
  <select id="top_search_select" name="entity_type">
     <option value="country">Countries</option>
     <option value="city">Cities</option>
     <option value="place" selected="selected">Tourist Attractions</option>
     <option value="hotel">Hotels</option>
  </select>
  <input type="submit" name="topsearch" class="submit" value="SEARCH" title="SEARCH"/>
</form>

and the autocomplete configuration looks like this:

<script type="text/javascript">
 //<![CDATA[
   var a = $('#q').autocomplete({
     serviceUrl:'/search',
     delimiter: /(,|;)\s*/, // regex or character
     maxHeight:400,
     width:325,
     zIndex: 9999,
     params: {entity_type:$('#top_search_select').val()},
     deferRequestBy: 0, //miliseconds
     noCache: false, //default is false, set to true to disable caching
     onSelect: function(value, data){window.location.replace(data);},
   });
 //]]>
</script>

Now the problem is in the backend i have different handlers that generate results for different types of entity that user would choose through the select option in the form.

By Default entity_type is place which is being passed just fine to the handler in the backend. However, what i want is when a person selects a different entity from the select box in the form params: {entity_type:$('#top_search_select').val()} in the script configuration also gets updated.

Any help or ideas will be much appreciated. Thanks.

like image 369
Amyth Avatar asked Jun 03 '12 07:06

Amyth


2 Answers

Alternatively, you can specify the params using a function which is evaluated just before the ajax request is sent.

$('#q').autocomplete({
    ...
    params: {
        'entity_type': function() {
            return $('#top_search_select').val();
        }
    }
    ...
});
like image 87
Pez Cuckow Avatar answered Sep 28 '22 07:09

Pez Cuckow


Might be an old question, but I feel that here's the best way to do it:

$('#q').autocomplete({
    ...
    onSearchStart: function(q) {
        q.entity_type = $('#top_search_select').val();
    }
    ...
});
like image 41
Stoked PHP Engineer Avatar answered Sep 28 '22 06:09

Stoked PHP Engineer