averageman
averageman

Reputation: 923

Twitter Typeahead remote

I am trying to use Twitter typeahead but I am facing a problem. I don't know how typeahead passes the string to the server. Is it through a GET parameter? If so, what is the name of the parameter?

Upvotes: 6

Views: 5473

Answers (2)

Peter Bob Ukonu
Peter Bob Ukonu

Reputation: 65

You might want to consider something like this, it is a very basic remote datasource example. The get parameter in this example is 'q'

// Get your data source
var dataSource = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: 'path/to/your/url/json/datasource/?q=%QUERYSTRING',
        wildcard: '%QUERYSTRING'
    }
});

// initialize your element
var $typehead = $('#form input').typeahead(null, {
    source: dataSource
});

// fire a select event, what you want once a user has selected an item
$typehead.on('typeahead:select', function(obj, datum, name) {
    //your code here
});

////////////////////////////////////
# in python (django) we get a query string using the request object passed through a view like this
query = request.GET.get('q') or ""
//the caveat [or ""] is just to prevent null exceptions

///////////////////////////////////
# using php
$query = ($_GET['q']) ? $_GET['q'] : "";

Upvotes: 1

Hieu Nguyen
Hieu Nguyen

Reputation: 8623

Easiest through a GET parameter, you can choose whatever parameter you want.

In JS:

$('#search').typeahead({
    name: 'Search',
    remote: '/search.php?query=%QUERY' // you can change anything but %QUERY, it's Typeahead default for the string to pass to backend
});

In PHP (or whatever backend you have):

$query = $_GET['query'];

Hope you get the basic idea.

Upvotes: 14

Related Questions