0

I am pulling stock symbols from Yahoo finance in a json object and I am trying to show them as a drop-down menu while the user starts typing the name of the company or the symbol in the search box .

Typeahead is not working as a drop down menu from the search box. This is the code I have so far.

If I dump the $data or $result in the suggest.php while substituting {$_POST['symbol']} with goog for example I am getting an array back. So, I am thinking that either suggest.php echo is not returning anything or suggest.php is not being called from the quote.js file.

If I remove the if statement in suggest.php and substitute {$_POST['symbol']} with goog and then go to http://localhost/suggest.php shouldn't echo print something?

Any help is appreciated. I am new to web development and trying to learn.

quote.js

$(document).ready(function() {

  // create autocomplete
  $('#form-quote input[name=symbol]').typeahead({

      // load autocomplete data from suggest.php
      source: function(query, callback) {
          $.ajax({
              url: '../suggest.php',
              type: 'POST',
              dataType: 'json',
              data: {
                  symbol: query
              },
              success: function(response) {
                  callback(response.symbols);

              }
          });
      }
  });

  // load data via ajax when form is submitted
  $('#form-quote').on('click', function() {

      // determine symbol
      var symbol = $('#form-quote input[name=symbol]').val();

      // send request to quote.php
      $.ajax({
          url: 'quote.php',
          type: 'POST',
          data: {
              symbol: symbol
          },
          success: function(response) {
              $('#price').text(response);
          }
      });


      return false;
  });

});

quote.php

<?php

//configuration
require("../includes/config.php");

//if form was submitted 

if($_SERVER["REQUEST_METHOD"] == "POST"){

    $stock = lookup(strtoupper($_POST["symbol"]));

    if(empty($_POST["symbol"])){

        //echo "You must enter a stock symbol";

    }else if($_POST["symbol"]){

    $price = number_format($stock['price'], 2);

    echo "A share of {$stock['name']} costs $$price";
    }
}

else{

    // render portfolio
render("stock_search.php", ["title" => "Get Quote"]);
}   
?>

quote_search.php

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

    <div class="control-group">
        <button type="submit" class="btn">Get Quote</button>
    </div>

</fieldset>
<div id="price"></div>
<div id="suggestions"></div> 
</form>
<script type="text/javascript" src="js/quote.js" ></script>

suggest.php

 <?php

// configuration
require("../includes/functions.php");

// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    // load suggestion data
$data = @file_get_contents("http://d.yimg.com/aq/autoc?query=  {$_POST['symbol']}&region=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks");

    // parse yahoo data into a list of symbols
$result = array();
    $json = json_decode(substr($data, strlen('YAHOO.util.ScriptNodeDataSource.callbacks('), -1));
    foreach ($json->ResultSet->Result as $stock)
        $result[] = $stock;

    echo json_encode(array('symbols' => $result]));
}

?>
tironci
  • 217
  • 1
  • 5
  • 19

1 Answers1

4

I see some typos. You might want to enable errors in php if this is a test server.

Anyway, from this code:

// load suggestion data
$data = @file_get_contents("http://d.yimg.com/aq/autoc?query=GOOG&region=US&lang=en-US&callback=YAHOO.util.ScriptNodeDataSource.callbacks");

// parse yahoo data into a list of symbols
$patt = array("/^YAHOO\.util\.ScriptNodeDataSource\.callbacks\(/","/\)$/");
$repl = array("","");
$json = json_decode(preg_replace($patt,$repl,$data));

foreach ($json->ResultSet->Result as $stock)
    $result[] = $stock;

echo json_encode(array('symbols' => $result));

I get the following output:

{"symbols":[{"symbol":"GOOG","name":"Google Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"^UVSPY","name":"NASDAQ OMX Alpha GOOG vs. SPY","exch":"NAS","type":"I","exchDisp":"NASDAQ","typeDisp":"Index"},{"symbol":"GOOG-U.TI","name":"GOOGLE-A","exch":"TLO","type":"S","exchDisp":"TLX Exchange ","typeDisp":"Equity"},{"symbol":"GOOG11BF.SA","name":"GOOGLE -DRN MB","exch":"SAO","type":"S","exchDisp":"Sao Paolo","typeDisp":"Equity"},{"symbol":"GOOG.MX","name":"Google Inc.","exch":"MEX","type":"S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GOOF.EX","name":"GOOGLE-A","exch":"EUX","type":"S","exchDisp":"EUREX Futures and Options Exchange ","typeDisp":"Equity"},{"symbol":"GGQ1.F","name":"GOOGLE-A","exch":"FRA","type":"S","exchDisp":"Frankfurt","typeDisp":"Equity"},{"symbol":"GGQ1.MU","name":"GOOGLE-A","exch":"MUN","type":"S","exchDisp":"Munich","typeDisp":"Equity"},{"symbol":"GGQ1.HA","name":"GOOGLE-A","exch":"HAN","type":"S","exchDisp":"Hanover","typeDisp":"Equity"},{"symbol":"GGQ1.DE","name":"GOOGLE-A","exch":"GER","type":"S","exchDisp":"XETRA","typeDisp":"Equity"}]}

With your data fetching and parsing corrected, if you are using Bootstrap 2.1+ you should be able to implement the ajax call to your PHP proxy as described in this answer. (Search the page for "Bootstrap 2.1" if the link doesn't jump down to it.)

Community
  • 1
  • 1
Rodney G
  • 4,746
  • 1
  • 16
  • 15
  • Thanks for your reply. I do get the same results as you. Is there a way to check if the ajax function is working right? I still cannot get the drop-down menu. – tironci Apr 02 '13 at 18:35
  • Update? You said I fixed the PHP output, but you didn't accept my answer. Did you update your ajax call per the answer I linked to? – Rodney G Apr 05 '13 at 15:50
  • I get the results with your changes but when I i try to get the results from ajax I still cannot get the drop-down menu. – tironci Apr 06 '13 at 13:02