How to pass selected value as extra parameter to ajax call

1k views Asked by At

my coding part

$("#demo-input").tokenInput("data/autosuggest-search-city.php", 
        {
            searchDelay: 2000,
            minChars: 3,
            tokenLimit: 10
        });

I want to send the selected values as extra parameter to "data/autosuggest-search-city.php".

For example, Initially I search and select one value from list then again searching, this time I want to send the 1st selected value to server.

How to do this?

1

There are 1 answers

3
Artur Filipiak On BEST ANSWER

TokenInput plugin doesn't support that natively.
You can however make a simple workaround to update "AJAX url" whenever a token is added or removed from selection.

Use onAdd and onDelete callbacks to trigger "AJAX url" changes;
Get selected tokens using selector.tokenInput("get") method;
Set the new "AJAX url" by updating .data("settings").url of the element;

// cache the original url:
var token_url = "data/autosuggest-search-city.php";

$("#demo-input").tokenInput(token_url, {
    searchDelay : 2000,
    minChars    : 3,
    tokenLimit  : 10,
    onAdd       : function(){
        urlChange.call(this);
    },
    onDelete    : function(){
        urlChange.call(this);
    }
});

function urlChange(){
    var tokens = '', token_list = $(this).tokenInput("get");
    // proceed if any token/s are selected:
    if(token_list.length){
        // loop through the selected tokens (if more than one is selected)
        $.each(token_list, function(i, token){
            // use token "id" (or "name" if you wish) and separate them with comma:
            tokens += token.id + ',';
        });
        // update url:
        $(this).data("settings").url = token_url + '?selected_tokens='+tokens.replace(/,+$/,'');
    }else{
        // leave original url if no tokens are selected:
        $(this).data("settings").url = token_url;
    }
};