Search code examples
facebookfacebook-graph-apitypeaheadtypeahead.jstwitter-typeahead

Using typeahead.js to return list of Facebook friends


I am using the Facebook Graph API to return a list of Facebook friends. I then want to run the returned JSON into Typeahead.js as follows:

$(document).ready(function () {
    $('input.friends').typeahead({
        name: 'friends',
        prefetch: 'https://graph.facebook.com/me/friends?access_token=<?php echo $access_token;?>',
        ttl: 0,
        template: [
            '<p class="name-tag">{{name}}</p>'
          ].join(''),
             engine: Hogan
    });
});

My corresponding HTML is as follows:

<input class="friends typeahead" type="text" placeholder="Start typing" id="friends">

But nothing is being returned using the prefetch (with hardcoded, local values, no problem). I am not seeing any errors in the console regarding cross-domain issues.

I am fairly sure this is because Typeahead hasn't been told how to handle the JSON structure, but I am unsure how to achieve this. I have tried implementing the templating system Hogan (which I will admit to being unfamiliar with) but this has not helped.

Any ideas much appreciated.

Many thanks


Solution

  • Solution below. Remember to include Hogan if you're using that as your templating engine, as I have done:

            $.get('https://graph.facebook.com/me/friends?access_token=<?php echo $access_token;?>', function(server_data){
    
                var rt = {};
                        for (var i in server_data.data)
                          rt[server_data.data[i].id] = {name:server_data.data[i].name, id:server_data.data[i].id},
                           //rt.push({name:server_data.data[i].name})
    
                  console.log(rt)
    
                $('input.friends').typeahead({
                  limit: 10,
                  name: 'friends',
                  valueKey: 'name',
    
                  local:rt,
                  template: [
                      '{{id}}',
                  ].join(''),
                  engine: Hogan
                });
              })