Typeahead Bloodhound POST request

Ablue picture Ablue · Feb 17, 2014 · Viewed 26.4k times · Source

I cannot seem to get a remote query to use POST properly.

var creditors = new Bloodhound({
    datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.value)
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "../getCreditors",
        replace: function(url, query) {
            return url + "#" + query;
        },
        ajax : {
            type: "POST",
            data: $.param({q: queryInput.val()})
        }
    }
});

the queryInput.val() does not get the current value of the object only the value at the time bloodhound object is instantiated. How can I get the query string into the ajax data options?

Answer

holylaw picture holylaw · Mar 21, 2014

You can use beforeSend of $.ajax

var creditors = new Bloodhound({
    datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.value)
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "../getCreditors",

        replace: function(url, query) {
            return url + "#" + query;
        },
        ajax : {
            beforeSend: function(jqXhr, settings){
               settings.data = $.param({q: queryInput.val()})
            },
            type: "POST"

        }
    }
});