stock quotes with javascript

Abraham Adam picture Abraham Adam · Mar 1, 2011 · Viewed 36k times · Source

Does anyone know a way to get live - or 20 minutes delayed - stock quotes using javascript? I looked at the google api at http://code.google.com/apis/finance/docs/finance-gadgets.html but it was very hard to get a working example.

has anyone got it to work to get quote for any stock, or found a better way ?

thank you.

Answer

troutinator picture troutinator · Mar 1, 2011

It took awhile but here is working code that uses Yahoo!'s YQL and jQuery:

<script type="text/javascript" src="jquery-1.5.1.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
            var symbol='goog';
            var callback = function(data) {
                    var price=data.query.results.span[0].content;
                    alert('Stock Price: ' + price);
                };

            var url = 'http://query.yahooapis.com/v1/public/yql';
            // this is the lovely YQL query (html encoded) which lets us get the stock price:
            // select * from html where url="http://finance.yahoo.com/q?s=goog" and xpath='//span[@id="yfs_l10_goog"]'
            var data = "q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fq%3Fs%3D" + symbol + "%22%20and%20xpath%3D'%2F%2Fspan%5B%40id%3D%22yfs_l10_" + symbol + "%22%5D'&format=json";
            $.getJSON(url, data, callback);
    });
</script>