Twitter Typeahead.js with Yahoo Finance in AJAX -
i trying couple new version of typeahead.js , using json needs pulled ajax , not json file have in examples. can't work, don't want cache json result or anything, want pull live yahoo.
my html input <input type="text" id="symbol" name="symbol" autofocus autocomplete="off" placeholder="symbol" onkeyup="onsymbolchange(this.value)" />
my ajax/php file has retrieve data (this part work, tested firebug)
header('content-type:text/html; charset=utf-8;'); $action = (isset($_get['action'])) ? $_get['action'] : null; $symbol = (isset($_get['symbol'])) ? $_get['symbol'] : null; switch($action) { case 'autocjson': getyahoosymbolautocomplete($symbol); break; } function getyahoosymbolautocompletejson($symbolchar) { $data = @file_get_contents("http://d.yimg.com/aq/autoc?callback=yahoo.util.scriptnodedatasource.callbacks&query=$symbolchar"); // parse yahoo data list of symbols $result = []; $json = json_decode(substr($data, strlen('yahoo.util.scriptnodedatasource.callbacks('), -1)); foreach ($json->resultset->result $stock) { $result[] = '('.$stock->symbol.') '.$stock->name; } echo json_encode(['symbols' => $result]); }
the js file (this i'm struggling)
function onsymbolchange(symbolchar) { $.ajax({ url: 'yahoo_autocomplete_ajax.php', type: 'get', datatype: 'json', data: { action: 'autocjson', symbol: symbolchar }, success: function(response) { $('#symbol').typeahead({ name: 'symbol', remote: response.symbols }); } }); }
i don't think i'm suppose attach typeahead inside ajax success response, don't see examples ajax (except previous version of typeahead)... see json response firebug after typing character input doesn't react good. guidance appreciated, i'm working on proof of concept @ point... it's worth know i'm using ajax because in https , using direct http yahoo api giving kind of problems chrome , new firefox insecure page.
update
to make work, hieu nguyen, had modify ajax json response echo json_encode(['symbols' => $result]);
instead echo json_encode($result);
, modify js file use code suggested here:
$('#symbol').typeahead({ name: 'symbol', remote: 'yahoo_autocomplete_ajax.php?action=autocjson&symbol=%query' });
i have in reverse, i.e: hook ajax call inside typeahead remote
handler. can try:
$('#symbol').typeahead({ name: 'symbol', remote: '/yahoo_autocomplete_ajax.php?action=autocjson&symbol=%query' });
you don't have create onsymbolchange()
function since typeahead take care of already.
you can filter , debug response backend using:
$('#symbol').typeahead({ name: 'symbol', remote: { url: '/yahoo_autocomplete_ajax.php?action=autocjson&symbol=%query', filter: function(resp) { var dataset = []; console.log(resp); // debug response here // filtering if needed response return dataset; } } });
hope helps!
Comments
Post a Comment