jamjam
jamjam

Reputation: 3269

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.

Upvotes: 5

Views: 3138

Answers (2)

Nobu
Nobu

Reputation: 10425

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

Upvotes: 2

C Blanchard
C Blanchard

Reputation: 1063

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

Upvotes: 5

Related Questions