How is error handling done with the new Typeahead with Bloodhound?
Asked Answered
L

3

8

I have an issue in which Typeahead simply stops working when the user federated session expires. I would like to be able to perform an action when the "remote" call for Typeahead fails. How is this handled with Typeahead in particular? Is there some sort of "error" callback like you would find in a typical ajax call? Here is the code that I currently have:

var hints = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "/ProjectAssociation/CountryLookup?query=%QUERY",
        wildcard: "%QUERY"
    }
});
$("#assocStoragesSelection").typeahead(null, {
    name: "nations",
    limit: 90,
    valueKey: "ShortCode",
    displayKey: "Name",
    source: hints,
    templates: {
        empty: [
            "<div class='noitems'>",
            "No Items Found",
            "</div>"
        ].join("\n")
    }
});
Liatris answered 4/4, 2016 at 13:42 Comment(2)
In that case you need to add a check in data returned from server;Henbane
Has my answer helped?Montenegro
M
2

Typeahead's Bloodhound suggestion engine is lacking in facilities to inform the user when there is a problem with a remote source.

Instead of using Bloodhound to get the suggestions you could instead use Typeahead's source source option (see here). By specifying your source here you can then handle errors and display a suitable message to the user.

I've created an example here:

http://jsfiddle.net/Fresh/oqL0g7jh/

The key part of the answer is source option code shown below:

$('.typeahead').typeahead(null, {
  name: 'movies',
  display: 'value',
  source: function(query, syncResults, asyncResults) {
    $.get(_url + query, function(movies) {

      var results = $.map(movies.results, function(movie) {
        return {
          value: movie.original_title
        }
      });

      asyncResults(results);
    }).fail(function() {
      $('#error').text('Error occurred during request!');
      setTimeout("$('#error').text('');", 4000);
    });
}

The source option is making use of jQuery's get method to retrieve the data. Any errors which occur are handled by the deferred object's fail method. In that method you can appropriately handle any errors and display a suitable message to the user. As the source function is specified with three parameters, this causes Typeahead to default this call as asynchronous, hence the call to:

asyncResults(results);
Montenegro answered 18/4, 2016 at 13:15 Comment(0)
J
6

The "right" way to handle errors is adding an error handler to the AJAX call, using the prepare function. If you are using the wildcard option, notice that prepare overrides it.

For example, you can turn this:

new Bloodhound({
    remote: {
        url: REMOTE_URL,
        wildcard: '%s'
    }
});

into this:

new Bloodhound({
    remote: {
        url: REMOTE_URL,
        prepare: function(query, settings) {
            return $.extend(settings, {
                url: settings.url.replace('%s', encodeURIComponent(query)),
                error: function(jqxhr, textStatus, errorThrown) {
                    // show error message
                },
                success: function(data, textStatus, jqxhr) {
                    // hide error message
                }
            });
        }
    }
});

The object returned by prepare is used as a settings object for jQuery.ajax() so you can refer to its documentation.

Johm answered 8/11, 2016 at 11:42 Comment(0)
M
2

Typeahead's Bloodhound suggestion engine is lacking in facilities to inform the user when there is a problem with a remote source.

Instead of using Bloodhound to get the suggestions you could instead use Typeahead's source source option (see here). By specifying your source here you can then handle errors and display a suitable message to the user.

I've created an example here:

http://jsfiddle.net/Fresh/oqL0g7jh/

The key part of the answer is source option code shown below:

$('.typeahead').typeahead(null, {
  name: 'movies',
  display: 'value',
  source: function(query, syncResults, asyncResults) {
    $.get(_url + query, function(movies) {

      var results = $.map(movies.results, function(movie) {
        return {
          value: movie.original_title
        }
      });

      asyncResults(results);
    }).fail(function() {
      $('#error').text('Error occurred during request!');
      setTimeout("$('#error').text('');", 4000);
    });
}

The source option is making use of jQuery's get method to retrieve the data. Any errors which occur are handled by the deferred object's fail method. In that method you can appropriately handle any errors and display a suitable message to the user. As the source function is specified with three parameters, this causes Typeahead to default this call as asynchronous, hence the call to:

asyncResults(results);
Montenegro answered 18/4, 2016 at 13:15 Comment(0)
C
0

try this code

var hints = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "/ProjectAssociation/CountryLookup?query=%QUERY",
        wildcard: "%QUERY",
        ajax: {
         error: function(jqXHR) {
          //do some thing
         }
    }
    }
});
Caulfield answered 11/4, 2016 at 18:55 Comment(3)
@BenSmith's answer is elegant, but if this one works than I believe it's the most succinct.Faints
@AngelJosephPiscola This answer wont work with the latest version of Bloodhound. The 'remote' option does not have an 'ajax' option. See hereMontenegro
This works great in 10.5...found this after several hours of searching and a bunch of other answers that only dealt with empty result sets as opposed to this one which handles actual errors returned by the remote url (401s etc).Aleph

© 2022 - 2024 — McMap. All rights reserved.