You are currently browsing the yalamber.com posts tagged: ajax


Anchor based permanent navigation for ajax pages

Ok here is how to make anchor based permanent navigation for your ajax pages. (* I’m using jquery as js library here)

var anchor_hash = $(document).attr('location').hash;

this code will pull the #part of the url

if you have url like http://www.example.com/page.php#welcome

it will pull #welcome to the anchor_hash variable in js.

So now you can use ajax to pull welcome page to show in the page.php

$.ajax({
url:'get_page.php',
type:'POST',
data:'page='+anchor_hash,
success:function(html){
$('div.content').html(html);
}
})

So now when you type in url http://www.example.com/page.php#welcome

the page.php will load welcome page always even when you refresh page.

Full example codes

following is your page.php

<html>
<head>
<title>welcome to anchor based navigation</title>
<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    var anchor_hash = $(document).attr('location').hash;
$.ajax({
url:'get_page.php',
type:'POST',
data:'page='+anchor_hash,
success: function(html){
$('div.content').html(html);
}
    });
});
</script>
</head>
<body>
<div class="content">
Welcome to example.com
</div>
</body>
</html>

Now in get_page.php we will load the requested page sent from ajax through page.php.

<?php
if(isset($_POST['page']))
{
switch($_POST['page'])
{
case 'welcome':
//load welcome page here
break;
case 'contact':
//load contact page here
break;
}
}
?>

So now whenever you go to http://www.example.com/page.php#welcome it will load welcome page and when you go to http://www.example.com/page.php#contact it will load you contact page


Tags