jQuery AJAX News Ticker

There are several jQuery News Tickers available but I needed one that I could control the output from PHP and add a slight blank delay between news items. This demo does not have the delay between items but you can add sleep() to ticker.php if needed. This script could be modified to create the data source (ticker.php) via MySQL or RSS feeds.

This script calls ticker.php for the first item to set in the ticker <div> and also set the total count for the javascript to loop through then calls the appropriate indexed item from the $json array in ticker.php.

For the impatient:
Demo of the jQuery AJAX News Ticker

PHP: ticker.php

if ($_GET['r'] == 1)
{
    // Removing browser caching
    header( "Expires: Mon, 20 Dec 1998 01:00:00 GMT" );
    header( "Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" );
    header( "Cache-Control: no-cache, must-revalidate" );
    header( "Pragma: no-cache" );
}

$json = array();

$json[] = array(
	'url' => '#1',
	'text' => 'First Item Text'
);

$json[] = array(
	'url' => '#2',
	'text' => 'Second Item Text'
);

$json[] = array(
	'url' => '#3',
	'text' => 'Third Item Text'
);

$json[] = array(
	'url' => '#4',
	'text' => 'Fourth Item Text'
);

if ($_GET['r'] == 1)
{
    echo json_encode(array($json[((int)$_GET['i'] - 1)]));
}

jQuery

<?php
// Call the ticker.php script to grab the first item and total items
require('ticker.php');
?>

var total = <?php echo count($json); ?>;
var current = 1;

$(document).ready(function(){
	setInterval("get_ticker()", 3000); // Change this to your specified need time, in milliseconds
});

function get_ticker()
{
	// Increment the counter
	if (current != total)
	{
		current  ;
	}
	else
	{
		current = 1;
	}

	// Get the data
	$.ajax({
		type: "GET",
		dataType: "json",
		cache: false,
		url: "ticker.php?i="   current   "&r=1",
		timeout: 2000,
		error: function() {
			alert("Failed to submit");
		},
		success: function(data) {
			$.each(data, function(i, j){
				$("#ticker-link").attr("href", j.url);
				$("#ticker-link").text(j.text);
			});
		}
	});
}

HTML

<div id="ticker">
	<!-- Display the first item -->
	<a href="<?php echo $json[0]['url']; ?>" id="ticker-link"><?php echo $json[0]['text']; ?></a>
</div>

Demo/Download

Download
Demo of the jQuery AJAX News Ticker

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter

Related Posts

  • No Related Post

Leave a Reply





Donate

If you found this article useful and would like to see more like it this please consider making a donation.

Sponsors