Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel pending bloodhound request in Twitter typeahead.js

I have twitter typeahead.js setup like this:

var filteredSource = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '@Url.Action("Get", "Search")/',
        prepare: function (query, settings) {
            settings.url = settings.url + $('#filter-select').val() + '?q=' + encodeURIComponent(query);
            return settings;
        },
        rateLimitBy: 'throttle',
        rateLimitWait: 800
    }
});

$('#search').typeahead({
    hint: false,
    highlight: true,
    minLength: 3
}, {
    name: 'filtered-source',
    display: 'value',
    limit: 50,
    source: filteredSource,
    templates: {
        empty: [
            '<div>',
            '&nbsp;&nbsp;Unable to find any results.',
            '</div>'
        ].join('\n'),
        suggestion: Handlebars.compile(templateData)
    }
});

When user makes a search and starts typing something like "key" and makes a pause, a search request is being sent to the server by bloodhound. When user then adds letters to the input field, another search is sent to the server for example "keyword".

But the pending request "key" is first being waited to be completed by the browser and then server processes the second request and only after it has completed, results are shown.

So it can take a long time before any results are seen by the user.

Is there a way to cancel the pending request through bloodhound when the keyword is changed?

like image 272
doze Avatar asked Nov 26 '25 21:11

doze


1 Answers

You can use abort() function like this:

var lastSearch;
var filteredSource = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: '@Url.Action("Get", "Search")/',
        prepare: function (query, settings) {
            settings.url = settings.url + $('#filter-select').val() + '?q=' + encodeURIComponent(query); 
            settings.beforeSend = function(e) {
                if (lastSearch) {
                     lastSearch.abort();
                }
                lastSearch = e;
            };
            return settings;
        },
        rateLimitBy: 'throttle',
        rateLimitWait: 800
    }
});

This will cancel the last AJAX request done although it is important to note that the abort function will not always prevent the request from reaching the server. If the request reaches the server before abort() is called, the server may continue to process the request.

like image 76
joalcego Avatar answered Nov 29 '25 11:11

joalcego



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!