user1721135
user1721135

Reputation: 7092

How can I reverse AJAX action on back button click?

I am trying to figure out history API but after reading the documentation I barely understand anything.

For example I have the following AJAX:

$("#hund").click(function(e) {
         e.preventDefault();
$(".result").load("hund.html #content", function() {
  });

The following browser URL manipulation:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

This I understand. Click something, change the url. Click back, change the url back.

But I want, if the back button is clicked after the AJAX click, I want the AJAX call to be reversed. In that case, that would be the result div to be emtpy again, or if you have clicked several things and then clicked back, the previous stuff to be loaded.

How would I achieve this effect?

Upvotes: 1

Views: 3293

Answers (2)

icktoofay
icktoofay

Reputation: 128991

Preserve the contents of the previous pages. For example:

var lastPage = $('.result').children().remove();
$('.result').load(...);

Then, when you want to go back, do something like this:

$('.result').empty().append(lastPage);

That's the basic principle, at least. In practice, if you want someone to be able to go back multiple times, then you can't just have one lastPage; you'll need to do something more complicated.

One more complicated way would be to keep an object with the contents of all the previous pages visited (cache). Then you might have a function navigate that looks like this:

var cache = {};
var currentPageName = /* something */;
function navigate(newPageName) {
    cache[currentPageName] = $('.result').children().remove();
    if(Object.prototype.hasOwnProperty.call(cache, newPageName)) {
        $('.result').append(cache[newPageName]);
        delete cache[newPageName];
    }else{
        $('.result').load(newPageName + ' #content');
    }
    currentPageName = newPageName;
    history.pushState(newPageName, newPageName, newPageName);
}

Then in onpopstate you can use navigate as well.

Upvotes: 1

cirrus
cirrus

Reputation: 5662

You need to modify the browser history manually. There are libraries for this.

See What's the best library to do a URL hash/history in JQuery?

Upvotes: 1

Related Questions