2

I am trying to use Bloodhound typeahead feature to be able to search a database on my flask application.

I followed along here: Twiiter Typeahead Custom Templates - Getting Default Example Working

$(document).ready(function(){
 var playerList = [{
"name": "Calvin Ridley",
"team": "ATL",
"id": 14
  }, {
    "name": "Rob Gronkowski",
    "team": "TB",
    "id": 15
  }];

  var players = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: $.map(playerList, function(d) {
      return {
        value: d.name,
        // pass `playerList` to `suggestion`
        suggest: d
      }
    })
  });

  players.initialize();

  $("#custom-templates .typeahead").typeahead(null, {
    name: "best-pictures",
    display: "value",
    source: players.ttAdapter(),
    templates: {
      notFound: [
        "<div class=empty-message>",
        "Unable to find any players that match the current query",
        "</div>"
      ].join("\n"),
      suggestion: function(data) {
        // `data` : `suggest` property of object passed at `Bloodhound`
        return "<div><strong>" + data.suggest.name + "</strong>" 
               + ' (' + data.suggest.team + ')' + "</div>"
      }
    }
  });

}); 

This works well but what I want to be able to do is instead use playerList defined by a json created with flask using jsonify.

@app.route('/players')
def playerdic():
    res=Player.query.all()
    list_players=[r.as_dict() for r in res]
    return jsonify(list_players)

This creates a json which I believe is identical to the one I created locally. Image of json found in /players

I think I need to use prefetch but I am not sure how to link it to the '/players' while still allowing me to use the function where I pass the d.name to the value and the d to the suggestion.

1 Answers1

0

I found my answer here.... Bloodhound / typeahead : using remote with simple strings

Specifically using the prefetch section:

$(document).ready(function(){
  var players = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url: "http://127.0.0.1:5000/players",
        filter: function(data){
            return $.map(data, function(item){
                return {
                 value: item.name + ' (' + item.team + ')',
                 suggest: item
                };
            });
        }
    }
  });

Although I do not like that I need to explicitly set the URL as 'http://127.0.0.1:5000/players'.