jqueryposttwitter-typeaheadbloodhound

Twitter's typeahead-bloodhound: What is the equivalent of "%QUERY" when using ajax.data and POST?


If one uses Bloodhound with GET:

// Typeahead
personsBloodhound = new Bloodhound({
    datumTokenizer: function (person) { return person.name; },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/ajax/Persons/List?nameContains=%QUERY',
        ajax: {
            beforeSend: function(xhr) {
                $(".searching-person").show();
            },
            data: {
                "pageSize": 4,
                "otherParam1": "blah",
                "otherParam2": "bleh",
            }
        },
        filter: function (response) {
            $(".searching-person").hide();
            return response.persons;
        }
    }
});

One simply uses %QUERY in the URL.

Now....
If one uses Bloodhound with POST, what should I use instead of %QUERY?

// Typeahead
personsBloodhound = new Bloodhound({
    datumTokenizer: function (person) { return person.name; },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '/ajax/Persons/List',
        ajax: {
            type: "POST",
            beforeSend: function(xhr) {
                $(".searching-person").show();
            },
            data: {
                "nameContains": ....WHAT GOES HERE?????......
                "pageSize": 4,
                "otherParam1": "blah",
                "otherParam2": "bleh",
            }
        },
        filter: function (response) {
            $(".searching-person").hide();
            return response.persons;
        }
    }
});

If it was not clear, the question is:
What is the equivalent of %QUERY when using POST within Bloodhound's remote?

The documentation isn't clear about this, (proof): https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#remote

Also tried using:

 "nameContains": $("#my-input-that-uses-typeahead").val(),

But didn't work.


Solution

  • You have to alter the URL somehow, otherwise the bloodhound wont send an other request (see https://stackoverflow.com/a/24025789/2175370) and livesearch/typeahead wont work.

    So ("#my-input-that-uses-typeahead").val() works just fine in combination with a dynamic URL (e.g.http://127.0.0.1:1234/REST_API/_search?useless=%QUERY) and a beforeSend-function in the ajax setttings.

    I gonna file an issue about this behaviour. Using the bloodhound for POST-requests ist VERY awkward and takes away the simplicity intended with typeahead.js.

    EDIT:

    Also make sure you set the new value for the data in beforeSend and set settings.hasContent = true. Otherwise the initial data will be used.

    Example on how it's done: https://github.com/twitter/typeahead.js/issues/542#issuecomment-29995960.