Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead Bloodhound POST request

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?

like image 621
Ablue Avatar asked Feb 17 '14 05:02

Ablue


2 Answers

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"

        }
    }
});
like image 51
holylaw Avatar answered Nov 20 '22 09:11

holylaw


You can use the prepare property with remote or prefetch, mind that the function signature changes. An example with prefetch:

var Bloodhound = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.whitespace,
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                prefetch: {
                    url: remote,
                    prepare: function (settings) {
                        settings.type = "POST";
                        settings.contentType = "application/json; charset=UTF-8";
                        return settings;
                    },
                    remote: function (query, settings) {
                        settings.type = "POST";
                        settings.data = {q: query, foo: 'bar'}; // you can pass some data if you need to
                        return settings;
                    }
                }
            });

Remember that with remote the function signature changes with function(query, settings).

For reference: github.com/twitter/typeahead.js/issues/1236

like image 13
Atropo Avatar answered Nov 20 '22 09:11

Atropo