user1775888
user1775888

Reputation: 3313

HTML5 history popstate with ajax, direct link not work

This Demo I want to click forward to content(index.php?id=id) click back to subject(index.php).

Q1. (index.php?id=id) direct link content page not available, it will show (index.php) subject , why?

Q2. Click back after the second times (forward > back > forward > back) then url will stop change, why? (Safari 5) update: Use window.onpopstate url works fine. Not get this error.


Any suggestion will be appreciated.

$(window).bind('popstate', function(){
    $.ajax({
        url:location.pathname,
        success: function(data){
            $('.container').html(data);
        }
    });
});

Demo

$('.subject').click(function(){
    $.ajax({
        url: 'index.php?id=' + $(this).attr('rel'),
            success: function(data){
                $('.container').html(data);
            }
    });
    var pageurl;
    pageurl = 'index.php?id=' + $(this).attr('rel');
    if(pageurl != window.location){
        window.history.pushState({path: pageurl}, "", pageurl);
    }
    return false;
});

index.php

<div class="container">
    <?php
        if($_GET['id']){
           ...
            print"<div class="content"></div>";
        }
        else{
           ...
           print"<div class="subject" rel="id"></div>"
        }
    ?>
</div>

Upvotes: 0

Views: 4470

Answers (2)

Arun David
Arun David

Reputation: 2784

You just have to fetch the page content(i.e. subject for your scenario) using ajax and show it in your page container. Consider if you are in 'index.php' and clicks on a subject.. so your url changes to 'index.php?id=7'. Now you are clicking back.. here in 'popstate' event, 'location.pathname' gives 'http://host/index.php'. Thats it, fetch the data from 'location.pathname' using ajax and show it.

$(window).bind('popstate', function(){
    $.ajax({
        url:location.pathname,
        success: function(data){
            $('.content').html(data);
        }
    });
});

Upvotes: 1

aziz punjani
aziz punjani

Reputation: 25796

The popstate event handler will receive an event object which contains the state you passed in to pushState. It's accessible via event.state Here's the event interface definition. Here's some demo code to illustrate the concept.

window.addEventListener("popstate", function(event) {
if( event.state !== null )    
    alert('Browser back button was clicked, state returned ' + JSON.stringify( event.state ) ); 
};

Upvotes: 1

Related Questions