June 22, 2010

Trigger Ajax function with back/forward actions?

Question by JasonS

Firstly I would just like to thank everyone for reading this and answering my questions. The help given to date has been invaluable and I a better programmer thanks to the help I have been given.

To the problem at hand. I fear it is a little rough but the script below for the most part works.

The problem is that while the history is stored, when a user goes back or forward the page doesn’t change. Do you have any idea what I can do to modify this so the go function is triggered?

$(document).ready(function(){

 $("a").click(function() {
  if (strpos($(this).attr('href'), 'mob.php') !== false) {
   window.location = url($(this).attr('href'));
   go(idToPath($(this).attr('href')));
   return false;
  }
 });
});

function go(num) {
 if (num != undefined) {
  $.ajax({
   url: "mob.php?p="+num+"&logo=0",
   cache: false,
   success: function(html){
    $("#ajax").html(html);
   }
  });
 }
}

$.history.init(function(u) {});
var page = 4;
var id = window.location.hash.substr(1);
if (id != '' && page != id) {
 go(id);
}

Answer by Ragnis

There isn’t such event.

But you could use some history plugin, on see, how its done there:
http://www.mikage.to/jquery/jquery_history.html

Answer by Starx

Well, I am not sure of any fixed solution to this problem.

But I came up with a temporary solution for this.

  1. At the begining of every page navigated through Ajax, I store the page info and additional parameters. like $_SESSION['page'][] = "book.php?cat=1"
  2. Attach a function to browser’s history event and call a custom function to fetch the required URL and redirect to it.

This is not much of a answer, but this should give you a rough idea. 🙂

...

Please fill the form - I will response as fast as I can!