Scriptplayground

 Print Page | Close Window

Displaying Stock Tickers using AJAX and PHP

Learn how to create an interactive stock ticker using AJAX and PHP.

Once you begin to develop applications and web sites using Javascript, the next logical step is to add interactivity on your page. The limits of this process are non-existent, but for this tutorial you will learn how to create an interactive stock ticker application.

One thing to note is this tutorial is meant to get the ball rolling when using AJAX and PHP.

Getting Started

Before beginning the development process of this tutorial, let's start with downloading and testing out jQuery. jQuery is a Javascript framework made popular because its extensive code and documentation. This will be the framework used in this tutorial and once you learn the basics you will be using jQuery in pretty much all of your Javascript projects.

In order to download the jQuery library simply point your web browser to jquery.com and click the download button as shown in figure 1.


Figure 1: The jQuery download link found on the libraries home page.

Now that you have downloaded jQuery, the next step is to create an new HTML file with the skeleton of the application, as shown below. Once you have created this file, save it as ajax-stock.html in the same directory you saved the jQuery Javascript file in.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head>
		<title>Stock Ticker using Ajax</title>		
		<script type="text/javascript" src="jquery-1.3.min.js"></script>
		
		<!-- Add Javascript code here -->
		<!-- Add Style code here -->
		
	</head>
	<body>
	<h2>Stock Ticker using AJAX</h2>
	</body>
</html>

Adding the HTML

Now while still in the HTML code, add in the form and table code within the <body> tags that is displayed below.

<form id="add-stock">
	<input type="text" id="stock" name="stock" value="adbe,siri" />
	<input type="button" value="Get Stock Data" id="addStockBtn" />
	<small>( separate multiple tickers with a "," )</small>
</form>

<table id="stocks">
	<tr>
		<td colspan="3">Enter a ticker above to begin searching.</td>
	</tr>
</table>

Now that the HTML is completed, add some simple CSS to enhance the style of the application.

<style type="text/css">

#stocks {
	width: 600px;
}
#stocks thead {
	font-weight: bold;
}

#add-stock {
	margin-bottom: 10px;
	background-color: #eeeeee;
	padding: 10px;
}

</style>

Now if you save this file and open it in your web browser you will see a form and button, as shown in figure 2.


Figure 2: The un-styled form with input and submit button.

Finally adding the Javascript

So, at this point you have a really cool HTML form where you can add stock tickers, but no way to actually load anything. The next step is to add in the Javascript code that will load the stock data and display it in the table.

This tutorial is not intended to be an extensive overview of jQuery, their site already covers that pretty well. However, while following the jQuery based tutorials found on this site you will begin to pick things up quickly.

Now add the <script> block in the head section of the HTML file you created during the beginning of this tutorial. Once that is created, add the following Javascript code.

<script>

var stockURL = "stock-ticker.php?tickers=";

var stockTickers = new Array();

$(document).ready(function(){
	
	$("#addStockBtn").click(function(e){
	
		var stock = $("#stock").val();
		
		$.get(stockURL + stock, function(data){
			
			var linesOfData = data.split('\n');
			
			$("#stocks").empty();					
			$("#stocks").append(""
				+ "Stock"
				+ "Value"
				+ "Change"
				+ "");
			
			for(i=0; i < linesOfData.length-1; i++)
			{
				var lineOfData = linesOfData[i].split(',');
				$("#stocks").append("" 
					+ String(lineOfData[0]).replace(/\"/g, '') 
					+ "" + lineOfData[1] 
					+ "" + lineOfData[2] 
					+ "");
			}				
		});
	});
});

</script>

Now once you save the file you will be able to click the Submit button, but nothing will actually happen because you will notice the PHP file hasn't been created yet.

You may be asking yourself why a PHP file is even needed when you are just calling a URL on the Yahoo! server? Well, AJAX is not allowed to contact other sites, it must only load data from the host server, to prevent cross-site scripting attacks. Using PHP to load the Yahoo! data is a way to get around this because PHP (under normal installation) is able to load remote data and pass it back to Javascript.

Now open a new text file and save it with the file name stock-ticker.php. Once the file is created, add the following PHP code, which is used to load the data from Yahoo! Finance.

<?php

class YahooStocks
{

	private $yahooURL = "http://finance.yahoo.com/d/quotes.csv?s=";
	
	public function getStock($tickers)
	{
		$url = sprintf($this->yahooURL . "%s&f=sl1c1", $tickers);	
		return readfile($url);
	}

}

$yahooStocks = new YahooStocks();
print $yahooStocks->getStock($_GET['tickers']);

?>

Now that all of the files are created and written, the final step is to test it out. Basically enter any number of stock tickers (separating each with a ,) and click "Get Stock Data".

Wrapping things up

I hope you have enjoyed this tutorial using AJAX and PHP, in the future we will explore more advanced topics, such as developing content management systems, forms and other interactive modules. I do recommend you explore the jQuery documentation as it is quite extensive and will really help you out.

The complete source has been provided for your reference.


Find this article at:
http://scriptplayground.com/tutorials/js/Displaying-Stock-Tickers-using-AJAX-and-PHP/