My highstocks chart fetches JSON data from Yahoo and data structure is in the format of "www.blahAAPLblah.com".
I am trying to dynamically change the value of AAPL in the URL to other company ticker symbols so that I can fetch the data and display it on my chart. When manually changing the string to GOOG, it works fine. Additionally, setting var ticker = 'GOOG'
and modifying the URL to "www.blah" + ticker + "blah.com"
also produces the desired result.
However, when attempting to use a user input box with
var ticker = document.getElementById('userInput').value;
, everything stops working.
Any suggestions to resolve this issue would be greatly appreciated.
Here is the current state of my code: http://jsfiddle.net/SgvQu/
UPDATE: I have tried implementing JSONP for the request but the chart still fails to load.
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
// Storing closing prices in an array and converting to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
// Displaying values in the closePrices array
console.log( closePrices );
// Storing dates in an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
// Converting all dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
// Displaying the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Creating the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}