jQuery AJAX News Ticker
« Return to ArticleDemo
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>
Donate
If you found this article useful and would like to see more like it this please consider making a donation.
