Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can typeahead.js make cross domain requests?

Typeahead.js is a very popular autosuggestion library from Twitter.

I just installed and it does not seem to support cross domain requests via JSONP. I get the error about remote origin not allowed.

I have googled around and I can't find anything related to it.

Can anyone confirm if this functionality is supported or not.

like image 592
jamjam Avatar asked Aug 29 '13 17:08

jamjam


2 Answers

Regarding your first issue, judging by your error message, you may not have implemented it correctly because typeahead is not executing a JSONP request.

As of Typeahead.js v0.9.3 you can execute a JSONP request by passing 'jsonp' as the dataType, like this:

$('.typeahead').typeahead({
  name: 'jsonpExample',
  remote: {
    // ...
    dataType: 'jsonp'
  }
});

You'll find that typeahead will now execute JSONP requests.

UPDATE

In answering your second issue. The author has targeted to support JSONP - and by and large it does work - but it doesn't work properly in some edge cases in the current version.

For instance, if you need to trigger an JSONP request using a query other than "callback", you're going to be stuck. In this or a similar situation, you have two options:

1) Patch typeahead.js yourself to get JSONP working. The callback name issue, for instance, can be fixed by a simple solution

2) Wait for v0.10 to be released when the full jQuery AJAX object is exposed. Unfortunately it's a month past its promised delivery date and there are no indications it will be finished in the coming weeks

like image 121
C Blanchard Avatar answered Sep 21 '22 18:09

C Blanchard


With 0.10.5, it works over remote servers. On top of C Blanchard's answer, I needed jsonp attribute in ajax.

var items = new Bloodhound({
  ...
  remote: {
    url: 'http://localhost/api/items?q=%QUERY',
    ajax: {
      jsonp: 'callback',
      dataType: 'jsonp'
    }
});
items.initialize()
...
$('.typeahead').typeahead(null, {
  ...
  source: items.ttAdapter()
});
like image 43
Nobu Avatar answered Sep 19 '22 18:09

Nobu