mSatyam
mSatyam

Reputation: 541

Bootstrap typeahead not working with dynamic array retrieved from a php page

I was trying to create a autocomplete box that gets stock symbols and names from finance.yahoo.com according to the user query typed in typeahead text box.

I created a quote_form.php page in which there is a text box on which i applied jquery keyup function to get the characters when typed by the user and then based on that characters i made a get request inside my typeahead function on my php page called symbols.php which inturn calls this link below:

http://d.yimg.com/aq/autoc?query=$search&region=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks

In the above link $search contains the characters received by get request and then in response i received JSON data with some junk i cleared the junk and then made it a legitimate JSON data and from that JSON data i created a string that looks like javascript array with the field i needed from the JSON. So, when my quote_form.php receives that data it does not shows it in typeahead. I surely receive data as i have seen in chrome's inspect element's Network tab. The code for both the pages is as below, i have created a seperate html header so i will not include the same as it is not necessary:

I have included the necessary javaScript files and CSS files:

jquery version used: 1.8.2

Bootstrap version used: v2.2.1

quote_form.php

    <script type ="text/javascript">
    $(document).ready(function () {
    var key;
    $("input[name='symbol']").keyup(function() {
        console.log("Key pressed");
        window.key = $(this).val();
    });

    $("input[name='symbol']").typeahead({
        source: function(query, process) {
        return $.get('symbols.php', {s: window.key}, function(data) {
            console.log(data);
            return process(data);
            });
        }
    });

});

</script>

<form action="quote.php" method="post">
    <fieldset>
        <div class="control-group">
            <input id = "sy" autofocus autocomplete ="off" name="symbol" placeholder="Symbol" type="text"/>
        </div>
        <div class="control-group">
            <button type="submit" class="btn">Get Quote</button>
        </div>
    </fieldset>
</form>

symbols.php

<?php
    $search = $_GET['s'];

    $url = "http://d.yimg.com/aq/autoc?query=$search&region=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks";

    $raw_data =  @file_get_contents($url);

    $json = substr($raw_data, strpos($raw_data,'Result"') - 1);
    $json = rtrim($json, '})');
    $json = "{" . $json . "}";

    $result = json_decode($json, true);

    $jsarr = "[";
    foreach($result as $symbols)
    {
    foreach($symbols as $symbol)
    {
        $jsarr .= "'".$symbol['name'] . " " . $symbol['symbol'] . "', ";
    }
    }

    $jsarr .= "]";

    echo $jsarr;
?>

I also tried the above code without converting to JavaScript array i.e i also tried with JSON only but that didn't work either. Seen many examples on internet also but still i am missing something don't know what. If any body can figure out what i am doing wrong that would be a great relief for me.

Thanks in advance.

Upvotes: 2

Views: 1016

Answers (1)

omma2289
omma2289

Reputation: 54619

The Yahoo API is actually returning a JSONP callback, you can avoid the parsing by making a jsonp request directly from jquery, you just need to build the YAHOO object that's specified in the callback:

var $typeaheadInput = $("input[name='symbol']");
$typeaheadInput.typeahead({
    source: function (query, process) {
        return $.ajax({
            url: 'http://d.yimg.com/aq/autoc?query=' + query + '&region=US&lang=en-US',
            dataType: 'jsonp',
            jsonpCallback: 'YAHOO.util.ScriptNodeDataSource.callbacks'
        });
    }
});

//Build YAHOO object with callback function
YAHOO = {
    util: {
        ScriptNodeDataSource: {
            callbacks: function (data) {
                var sourceArray = $.map(data.ResultSet.Result, function (elem) {
                    return elem.name + ' - ' + elem.symbol;
                });
                $typeaheadInput.data('typeahead').process(sourceArray);
            }
        }
    }
};

Here's a working fiddle

Note: I removed the autofocus attribute from the input because it was causing issues with the typeahead dropdown

Upvotes: 1

Related Questions