Monday, April 18, 2016

How is error handling done with the new Typeahead with Bloodhound?

Leave a Comment

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")     } }); 

2 Answers

Answers 1

The Typeahead 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 Datasource source facility (see here). By specifying your source in 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 here:

$('.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 fail promise 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); 

Answers 2

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          }     }     } }); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment