<div id="rounded">
<div id="rounded">
<img src="img/top_bg.gif" alt="top" /><div id="main" class="container">
<h1>A simple AJAX driven jQuery website</h1>
<h2>Because simpler is better</h2>
<ul id="navigation">
<li><a href="#page1">Page 1</a></li>
<li><a href="#page2">Page 2</a></li>
<li><a href="#page3">Page 3</a></li>
<li><a href="#page4">Page 4</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
<div class="clear"></div>
<div id="pageContent">
Hello, this is a demo for a <a href="http://tutorialzine.com/2009/09/simple-ajax-website-jquery/" target="_blank">Tutorialzine tutorial</a>. To test it, click some of the buttons above. Have a nice stay!</div>
</div>
<div class="clear"></div>
<img src="img/bottom_bg.gif" alt="bottom" /></div>
</div>
Code (JavaScript)
$(document).ready(function(){ //executed after the page has loaded
checkURL(); //check if the URL has a reference to a page and load it
$('ul li a').click(function (e){ //traverse through all our navigation links..
checkURL(this.hash); //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)
});
setInterval("checkURL()",250); //check for a change in the URL every 250 ms to detect if the history buttons have been used
});
var lasturl=""; //here we store the current URL hash
function checkURL(hash)
{
if(!hash) hash=window.location.hash; //if no parameter is provided, use the hash value from the current address
if(hash != lasturl) // if the hash value has changed
{
lasturl=hash; //update the current hash
loadPage(hash); // and load the new page
}
}
function loadPage(url) //the function that loads pages via AJAX
{
url=url.replace('#page',''); //strip the #page part of the hash and leave only the page number
$('#loading').css('visibility','visible'); //show the rotating gif animation
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "load_page.php",
data: 'page='+url, //with the page number as a parameter
dataType: "html", //expect html to be returned
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$('#pageContent').html(msg); //load the returned html into pageContet
$('#loading').css('visibility','hidden'); //and hide the rotating gif
}
}
});
}
load_page.php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.php'))
echo file_get_contents('pages/page_'.$page.'.php');
else echo 'There is no such page!';