Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » js » Displaying Stock Tickers using AJAX and PHP

Displaying Stock Tickers using AJAX and PHP

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

View an Example of this article before you get started.

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.

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Displaying Stock Tickers using AJAX and PHP

 tutorialand  Thu Jan 22, 2009 7:27 am  
Nice tutorial!

Added to www.tutorialand.com
 diyan  Sun Jul 12, 2009 2:55 am  
not working, bicause this code old version
 mkeefe  Mon Jul 13, 2009 7:50 am  
@diyan - The example is still working for me, maybe jQuery has changed some things around.
  Stock Charts  Wed Aug 4, 2010 6:59 pm  
The demand for rich Internet applications (RIAs) such as complete storefronts and interactive surveys is skyrocketing, as is the pressure to create these dynamic apps overnight and at low cost.
 Stocks  Mon May 23, 2011 11:59 am  
It isn't working on either of my apache or TomCat servers. What kind of server will run the code?
 mkeefe  Tue May 24, 2011 7:33 am  
@Stocks - You may want to confirm PHP is properly configured on your servers by running a simple test, such as the following.

1. Start by creating a new file and name it "info.php".
2. Place the following contents in that file and save it.


<? phpinfo(); ?>


3. Finally upload the file to your web server and visit the new file in a web browser.

If everything worked properly you'll see a print out of PHP information, with no errors.

Hope that helps.
Matt
 Jacob  Mon Sep 12, 2011 1:01 pm  
The example link that you provided functions flawlessly. However, replication results in failure, which suggests potential errors in the php files that was pasted onto the web site.

If convenient, please consider copying and pasting the exact php file used in the example.

Thank you.
 mkeefe  Mon Sep 12, 2011 6:01 pm  
@Jacob - I just verified the included source code, please download/test with that. It may be a PHP configuration error on your server.
 Jacob  Mon Sep 12, 2011 7:19 pm  
Thank you mkeefe. I constructed a php which collects data from yahoo finance historical prices and it functions fine, so I am uncertain of the reason this one is not functioning.

I am able to output the data in php, however, I am attempting to learn to transfer it to javascript for processing (i.e., calculations), thus the need for the jquery.

I will reattempt again. Thank you for your efforts.
 Jacob  Mon Sep 12, 2011 8:12 pm  
Disregard my previous suggestion. The script functions flawlessly. Thank you. Now to learn from it.
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles