How do I pass an extra parameter to Jquery Autocomplete field?
Asked Answered
A

8

65

I'm using the JQuery Autocomplete in one of my forms.

The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.

This is how my form looks.

<form>

<select id="zipcode">

<option value="2000">2000</option>
<option value="3000">3000</option>
<option value="4000">4000</option>

</select>

<input type="text" id="product"/>

<input type="submit"/>

</form>

And here is the JQuery code:

$("#product").autocomplete
({
     source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
     minLength: 2,
     select: function(event, ui){

                             //action

                                 }
});

This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?

Ammoniate answered 12/9, 2010 at 2:53 Comment(0)
K
104

You need to use a different approach for the source call, like this:

$("#product").autocomplete({
  source: function(request, response) {
    $.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() }, 
              response);
  },
  minLength: 2,
  select: function(event, ui){
    //action
  }
});

This format lets you pass whatever the value is when it's run, as opposed to when it's bound.

Kinzer answered 12/9, 2010 at 9:8 Comment(8)
Hmmm. I can't seem to make it work using this method. Although it would be great if i could as it seems like a more elegant way of approaching the problem. Does the JSON data need to be structured differently? Do I still use $_GET['postcode'] && $_GET['term'] in my source file?Ammoniate
@Ammoniate - You'll just be using $_GET['postcode'] with the above code...if you want term on there, add it in by using this for the data argument: { term: request.term, postcode: $('#zipcode').val() }Kinzer
@Nick Still having trouble getting it working. I've made the change, but the autocomplete fails to materialise. Jquery is very new to me, so I'm not sure how to debug, but it seems to stop all code from my javascript file from working. I'm not sure what might be out of place, but the "request.term" is new to me.Just to clarify, this is the "term" that autocomplete creates as you type, right?Ammoniate
@Ammoniate - Correct that's where it comes from...the error was a missing comma after the source option in the above code see here, sorry! The console is the best place for debugging all JS errors, either Firebug or Chrome include excellent consoles for this.Kinzer
@Nick - Hi Nick, Hope you don't mind me asking but; Are you able to explain, or point me in the right direction to understanding, how the function(request, response) changes it from being when it's bound to being when it's run? - Also: is the response some type of output parameter, and where does the request parameter come from/get used? (I'm pretty new to this stuff atm). Cheers.Swept
@King - response is a function passed in when it's called, it's a callback function that itself takes a single parameter, the response text or data...that function sticks the data in the autocomplete widget. request is also provided, it's an object with a term property which is what's currently types in the box, it's passed in when the widget calls this method.Kinzer
Seems to be the cleanest method. I might recommend mentioning term: request.term in the answer itself, rather than solely as a comment.Calling
As mentioned by Nick, the "term: request.term" expression needs to be included within the curly brackets, otherwise you would not get a response for your search term, which is the whole purpose of the autocomplete function.Paunchy
A
37

This is not to complicated men:

$(document).ready(function() {
src = 'http://domain.com/index.php';

// Load the cities straight from the server, passing the country as an extra param
$("#city_id").autocomplete({
    source: function(request, response) {
        $.ajax({
            url: src,
            dataType: "json",
            data: {
                term : request.term,
                country_id : $("#country_id").val()
            },
            success: function(data) {
                response(data);
            }
        });
    },
    min_length: 3,
    delay: 300
});
});
Amoeba answered 26/2, 2014 at 23:4 Comment(1)
This method is the most clean and readable in my opinion. Works great, thanks.Aleciaaleck
V
9
jQuery("#whatJob").autocomplete(ajaxURL,{
    width: 260,
    matchContains: true,
    selectFirst: false,
    minChars: 2,
    extraParams: {  //to pass extra parameter in ajax file.
        "auto_dealer": "yes",
    },
});
Veasey answered 19/11, 2013 at 6:15 Comment(3)
It's now called just params. params: { "auto_dealer": "yes" },Wilfredowilfrid
easier then other answersMaitund
should be best answerMetchnikoff
S
6

I believe you are correct in thinking your call to $("#product").autocomplete is firing on page load. Perhaps you can assign an onchange() handler to the select menu:

$("#zipcode").change(resetAutocomplete);

and have it invalidate the #product autocomplete() call and create a new one.

function resetAutocomplete() {
    $("#product").autocomplete("destroy");
    $("#product").autocomplete({
         source:"product_auto_complete.php?postcode=" + $('#zipcode').val(),
         minLength: 2,
         select: function(event, ui){... }
    });
}

You may want your resetAutocomplete() call to be a little smarter -- like checking if the zip code actually differs from the last value -- to save a few server calls.

Sororicide answered 12/9, 2010 at 3:6 Comment(2)
Destroying the autocomplete widget and recreating it is tremendously wasteful, you should use the source argument as it was intended...Kinzer
@Footniko once loaded, I need to recreate it to change values, I'm using an extraParams and it doesn't update its value without doing this!Menchaca
D
3

This work for me. Override the event search:

jQuery('#Distribuidor_provincia_nombre').autocomplete({
    'minLength':0,
    'search':function(event,ui){
        var newUrl="/conf/general/provincias?pais="+$("#Distribuidor_pais_id").val();
        $(this).autocomplete("option","source",newUrl)
    },
    'source':[]
});
Delores answered 2/9, 2012 at 0:34 Comment(1)
Great, simple solution for setting the GET vars on the source url at the time of the search, not on page load. So much easier to read than having an AJAX call in the source functionInnoxious
L
1

Hope this one will help someone:

$("#txt_venuename").autocomplete({
    source: function(request, response) {
    $.getJSON('<?php echo base_url(); ?>admin/venue/venues_autocomplete', 
        { 
            user_id: <?php echo $user_param_id; ?>, 
            term: request.term 
        }, 
      response);
    },
    minLength: 3,
    select: function (a, b) {            
        var selected_venue_id = b.item.v_id;
        var selected_venue_name = b.item.label;            
        $("#h_venueid").val(selected_venue_id);
        console.log(selected_venue_id);            
    }
});

The default 'term' will be replaced by the new parameters list, so you will require to add again.

Lyon answered 26/7, 2018 at 2:49 Comment(0)
R
0
$('#txtCropname').autocomplete('Handler/CropSearch.ashx', {
    extraParams: {
        test: 'new'
    }
});
Reviel answered 29/12, 2014 at 10:34 Comment(0)
R
0
$('#product').setOptions({
    extraParams: {
        extra_parameter_name_to_send: function(){
            return $("#source_of_extra_parameter_name").val();
        }
    }
})
Rubetta answered 22/6, 2016 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.