typeahead.js icon indicating copy to clipboard operation
typeahead.js copied to clipboard

Show a spinner in the meantime the client is waiting for the results.

Open loalf opened this issue 13 years ago • 35 comments

First off, thanks for this library, it's just great.

I wonder whether it's possible to catch an event to show a spinner or something or the screen in the meantime the browser is waiting for the server to reply.

Thanks!

loalf avatar Apr 02 '13 14:04 loalf

Adding support for something like this has been brought up previously (see https://github.com/twitter/typeahead.js/issues/130#issuecomment-15446455). This is one of the next things I'll be working on.

jharding avatar Apr 02 '13 18:04 jharding

@jharding thanks, that would be brilliant!

loalf avatar Apr 04 '13 10:04 loalf

I was able to show the progress spinner with the following:

css:

.typeahead {
  background-color: #fff;
  background-repeat: no-repeat;
  background-position: 98%;
}

javascript:

typeaheadCtrl = $('.typeahead').typeahead({ name: 'countries', prefetch: '../data/countries.json' });

typeaheadCtrl.on('typeahead:initialized', function (event, data) {
   // After initializing, hide the progress icon.
   $('.tt-hint').css('background-image', '');
});

// Show progress icon while loading.
$('.tt-hint').css('background-image', 'url("/images/ajax-loader.gif")');

primaryobjects avatar Jul 16 '13 20:07 primaryobjects

I overcome this situation by making little changes, add these lines inside var Transport = function() {

this.xhrSending = o.xhrSending || function () { };
this.xhrDone = o.xhrDone || function () { };

And i changed _sendRequest function of Transport object like this

_sendRequest: function (url) {
    var that = this, jqXhr = pendingRequests[url];
    if (!jqXhr) {
        incrementPendingRequests();
        that.xhrSending(); // modification 1
        jqXhr = pendingRequests[url] = $.ajax(url, this.ajaxSettings)
                                        .always(always);
    }
    return jqXhr;
    function always() {
        decrementPendingRequests();
        pendingRequests[url] = null;
        if (that.onDeckRequestArgs) {
            that._get.apply(that, that.onDeckRequestArgs);
            that.onDeckRequestArgs = null;
        }
        that.xhrDone(); // modification 2
    }
}

And if we get to how you can implement it, As you can see in remote object there are xhrSending and xhrDone functions

var $ttHint = $(".tt-hint");
$txtAc.typeahead([
{
    minLength: 3,
    remote: {
        url: '/Search?q=%QUERY',
        xhrSending: function () {
            if (!$ttHint.length) {
                $ttHint = $(".tt-hint");
            }
            //add loading class to tt-hint element when request sending.
            $ttHint.addClass("loading");
        },
        xhrDone: function () {
            if (!$ttHint.length) {
                $ttHint = $(".tt-hint");
            }
            //remove loading class from tt-hint element when response arrived.
            $ttHint.removeClass("loading"); 
        }
    },
    name : 'searchResults'
    header: '<h3 class="ac-header">Search Results</h3>',
    template: document.getElementById("acTemplate").innerHTML,
    valueKey: 'title',
    engine: Handlebars,
    allowDuplicates : true
}
]);

There is loading css class

// added ! important because typeahead adding some styles to tt-hint that overrides background property.
.tt-hint.loading {
    background: transparent url('/images/ajaxloading.gif') no-repeat scroll right center content-box !important;
}

umitakkaya avatar Sep 22 '13 21:09 umitakkaya

@umitakkaya :+1:

gplesz avatar Oct 21 '13 15:10 gplesz

:+1:

messenjer avatar Oct 24 '13 16:10 messenjer

I used

    remote:{
        url: 'yourjsonlocation',
        beforeSend: function(xhr){
          showSpinner();
        },
        filter: function(parsedResponse){
            hideSpinner();
            return parsedResponse;
        }
    }

Really solved my problem. Phew

b3ckstage avatar Oct 28 '13 08:10 b3ckstage

Wouldn't it be cleaner to just fira a for example "typeahead:loading" event (and an event to indicate that it isn't loading anymore?) This way you can add an default implementation of a spinner but also use custom handling.

apfelbox avatar Dec 16 '13 10:12 apfelbox

Has there been any progress regarding this? It's a requested feature for the project I'm working on, but before I hack something together, I wanted to check if this was going to be implemented in the near future anyway.

Thanks for the great plugin!

Nevon avatar Feb 26 '14 10:02 Nevon

I'm not aware of anything.

jharding avatar Mar 07 '14 07:03 jharding

:+1:

lgoudriaan avatar Mar 21 '14 13:03 lgoudriaan

As we don't have events dispatching in Bloodhound for now, it's possible to monkey-patch its "transport" layer to be notified of Ajax requests:

var _transport = myBloodhoundInstance.transport, _transportGet = _transport.get;
myBloodhoundInstance.transport.get = function (url, ajax, handleRemoteResponse) {
  displayLoadingProgress();
  _transportGet.apply(_transport, arguments);
};

And we can hide the loading progress in the filter function, as described upper in this Issue comments.

olivierphi avatar Mar 24 '14 09:03 olivierphi

Hopefuly 0.10.3 will include support for this. In the meantime I've incorporated the handler in Svakinn's fork of 0.9.3.

Works well enough for now, although some of his other updates look awesome too.

stemwinder avatar Apr 22 '14 12:04 stemwinder

Has there been any updates on this? I use typeahead in a lot of areas, so a global solution would be awesome.

bassrock avatar Jun 18 '14 17:06 bassrock

Just to elaborate on @b3ckstage 's solution, this is actually quite clean--no patching or forking of anything required:

Since the remote configuration object allows you to pass parameters through to the jQuery ajax object, all you have to do is pass a beforeSend and a complete callback, and you find out whenever the AJAX call begins and ends. I'm doing this, for example, which is slightly different from what he did:

    var groupPrincipals = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: '/api/groupprincipals?search=%QUERY',
            filter: function(parsedResponse){
                return parsedResponse['groupPrincipals'];
            },
            ajax: {
                beforeSend: function(){ Ember.Logger.info("beforeSend callback called!"); },
                complete: function(){ Ember.Logger.info("complete callback called!"); }
            }
        }
    });

And it works fine (so far) in stock 0.9! I agree it would be nice if bloodhound emitted its own events, but as right now it doesn't emit any events, adding events just for this seems like overkill, if the above facility to hook into the jQuery ajax object's callbacks works fine. Or if there's something I'm missing with the above solution, do please mention it!

SphtKr avatar Jun 20 '14 08:06 SphtKr

@SphtKr great solution. that worked, it would also be good though if the typeahead had a flag to enable a spinner on its own though.

bassrock avatar Jun 25 '14 23:06 bassrock

This one worked for me:

var twitterAccounts = new Bloodhound({
     datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
     queryTokenizer: Bloodhound.tokenizers.whitespace,
     remote: {
          url: '/whatever/twitter/?q=',
          replace: function(url, query){
               Ember.$('.tt-hint').css('background-image', 'url("/res/AjaxLoader.gif")');
               Ember.$('.tt-hint').css('background-repeat', 'no-repeat');
               return url+encodeURIComponent(query);
           },
           filter: function(parsedResponse){
               Ember.$('.tt-hint').css('background-image', '');
               return parsedResponse;
           }
     },
     limit: 10
});

junssi avatar Jul 23 '14 06:07 junssi

In v0.11 (it's currently a WIP), I've added the follow events:

  • typeahead:asyncrequest
  • typeahead:asynccancel
  • typeahead:asyncreceive

The goal of these events is to solve the issues brought up in this thread – basically add hooks for async data operations.

jharding avatar Aug 18 '14 05:08 jharding

Great! Thank you very much!

olivierphi avatar Aug 18 '14 09:08 olivierphi

Thank you very much for your hard work!

stemwinder avatar Aug 18 '14 14:08 stemwinder