Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using the HighStocks javascript library to create a chart on my website using finance data taken from Yahoo.

I have an external javascript file with these functions:

JavaScript
//uses AJAX call to retrieve data and then creates the chart with the data
function createChart(ticker) {

    $.ajax({
        type: 'post',
        url: 'http://...' + ticker + '....com',
        success: function (data, status) {
        //chart is rendered in here
        }

//gets the user inputted ticker symbol from a HTML input box
// and passes to chart function
function getTicker() {
    var ticker = document.getElementById('userInput').value;
    createChart(ticker);
}


My HTML file just has a simple form with an input box and a button that when clicked calls the getTicker function. For some reason the AJAX call doesnt seem to work when I try to give it a new URL with user inputted parameters.

Can anybody see what I am doing wrong? Any suggestions would be appreciated.
Posted

1 solution

Hello,

Hello,

Generally your URL will be fix, what's going to change is the data you will be sending, which can either be sent as query string parameters or as POST request parameters. Since you are using POST request, your code should look something like
JavaScript
//uses AJAX call to retrieve data and then creates the chart with the data
function createChart(ticker) {
    $.ajax({
        type: 'post',
        url: 'http://your chart service url',
        data: {"chartData": ticker},
        success: function (data, status) {
            //chart is rendered in here
        }
    });
 
//gets the user inputted ticker symbol from a HTML input box
// and passes to chart function
function getTicker() {
    var ticker = document.getElementById('userInput').value;
    createChart(ticker);
}

For more information please have a look at JQuery documentation.

Working sample
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"></meta>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<meta name="author" content="Prasad P. Khandekar"></meta>
<meta name="owner" content="Fundtech INDIA Ltd."></meta>
<meta name="copyright" content="Fundtech INDIA Ltd."></meta>
<meta http-equiv="Expires" content="0"></meta>
<meta http-equiv="Pragma" content="no-cache"></meta>
<meta http-equiv="Cache-Control" content="no-cache"></meta>
<meta http-equiv="Pragma-directive" content="no-cache"></meta>
<meta http-equiv="cache-directive" content="no-cache"></meta>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/highstock.js"></script>
<script type="text/javascript" src="js/highcharts-more.js"></script>
<script type="text/javascript" src="js/modules/exporting.js"></script>
<script type="text/javascript">
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
var ticker = "Stock Quotes";

//var ticker = userInput.value;
//alt: try calling the function with the URL normal to see if calling the funciton is the problem.
function renderChart(data, status, jqXHR) {
	console.log(status);
	console.log(data);

	//Put all the closing prices into an array and convert to floats
	for (var i = 0; i < data.query.results.quote.length; i++) {
		closePrices[i] = parseFloat(data.query.results.quote[i].Close);
	}

	//displays the values in the closePrices array
	console.log(closePrices);

	//Put all the dates into an array
	for (var i = 0; i < data.query.results.quote.length; i++) {
		dateArray[i] = data.query.results.quote[i].date;
	}

	//Convert all the 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);

	//displays the dateArray
	console.log(dateArray);
	console.log(timeStampArray);

	// Create the chart
	$('#container').highcharts('StockChart', {
		rangeSelector: {
			selected: 1
		},
		title: {
			text: 'AAPL Stock Price'
		},
		series: [{
			name: ticker,
			data: closePrices
		}]
	});
}

function createChart(ticker) {
	$.support.cors = true;
	//Ajax call retrieves the data from Yahoo! Finance API
	$.ajax({
		type: 'GET',
		async: false,
		dataType: "json",
		url: 'http://query.yahooapis.com/v1/public/yql',
		data: { q:'SELECT * FROM yahoo.finance.historicaldata WHERE symbol="MSFT" AND startDate="2013-01-01" AND endDate="2013-04-3"',
				format:'json', diagnostics:true, env:'store://datatables.org/alltableswithkeys'},
		crossDomain:true,
		success: function (data, status, jqXHR) {
		    renderChart(data, status, jqXHR);
		},
		error: function (jqXHR, status, error) {
			console.log('Error: ' + error);
		}
	});
}

//Function to get ticker symbol from input box.
function getTicker() {
	ticker = document.getElementById('userInput').value;
	createChart(ticker);
	return false;
}
</script>
</head>
<body>
	<form id="form" method="POST">
		<h3>Enter the ticker symbol of the company you wish to view:</h3>
		<input type="text" id="userInput">
		<button type="button" onclick="getTicker();">Get Chart</button>
	</form>
	<div id="container" style="height: 500px; min-width: 500px">&nbsp;</div>
</body>
</html>


Regards,
 
Share this answer
 
v2
Comments
Member 9592868 7-Apr-13 15:53pm    
Thank you for the suggestion. I have tried changing my code but it is still not working. Here is a jsFiddle of my code: http://jsfiddle.net/SgvQu/
Prasad Khandekar 8-Apr-13 4:34am    
Hello,

I have gone through the sample on jsfiddle and tried to make it work on local machine. What I have discovered is that you need to have reference to following js files. There seems to be some issue with the chart data as well.

<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/highstock.js"></script>
<script type="text/javascript" src="js/highcharts-more.js"></script>
<script type="text/javascript" src="js/modules/exporting.js"></script>
Member 9592868 8-Apr-13 11:27am    
I appreciate your suggestions but unfortunately I have referenced the js files you have mentioned and it still does not work.
Prasad Khandekar 8-Apr-13 12:20pm    
The problem is in $('#container').highcharts function. Changing it to following rendered the chart.

// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector: {selected: 1},
title: {text: 'AAPL Stock Price'},
series: [{
name: ticker,
data: closePrices
}]
});

Regards,
Member 9592868 9-Apr-13 12:16pm    
I was unable to get this to work and so I have re-written the code using JSONP as other people suggested it was a JSON cross domain problem. However this still does not work! I have posted my code here: http://www.codeproject.com/Questions/575043/ChangeplusAJAXplusURLplususingplusJSONP

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900