Damian Doman Damian Doman - 15 days ago 7
Ajax Question

AJAX/PHP/JS - Cannot load page content into container

i keep on getting 'There is no such page!' message anytime i try to use the buttons to change the content.

Here is the index.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>eWorld</title>
<link rel="stylesheet" type="text/css" href="/css/style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>

</head>

<body>

<div id="rounded">
<div id="main" class="container">
<h1>eWORLD</h1>
<h2>You make difference.</h2>

<ul id="navigation">
<li><a href="#forum">Forum</a></li>
<li><a href="#about">About</a></li>
<li><a href="#register">Register</a></li>
<li><a href="#login" target=pageContent>Login</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div id="pageContent">
</div>
<div class="clear"></div></div>
<div align="center" class="#footer">eWorld</div>

</body>
</html>


The script.js:


var default_content="";
$(document).ready(function(){

checkURL();
$('ul li a').click(function (e){

checkURL(this.hash);

});

default_content = $('#pageContent').html();


setInterval("checkURL()",250);

});

var lasturl="";

function checkURL(hash)
{
if(!hash) hash=window.location.hash;

if(hash != lasturl)
{
lasturl=hash;

if(hash=="")
$('#pageContent').html(default_content);

else
loadPage(hash);
}
}


function loadPage(url)
{
url=url.replace('#page','');

$('#loading').css('visibility','visible');

$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){

if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}

});

}


Also, the load_page.php:

<?php
if(!$_POST['page']) die("0");

$page = $_POST['page'];

$newstr = str_replace("#","", $page);

if (!file_exists('pages/'.$newstr.'.html'))
echo file_get_contents('pages/'.$newstr.'.html');

else echo 'There is no such page!';
?>


It seems like the script is working fine, but somehow it couldn't get into the directory of new pages (which is /pages/forum.html ; /pages/login.html and so on).
Would be grateful if somebody could show me where have I made the mistake... :)

Answer

You are trying to get .hash of DOM element:

$('ul li a').click(function (e){
    checkURL(this.hash);

Instead get the href attribute:

checkURL(this.attr("href"));

.hash only works on URL object

Also, this first use of checkURL(); after documentReady should be throwing errors as it does not match the method definition