0

I am working with AJAX content. Basically a bunch of products are on one page and when you click a product it currently goes to the product without having to reload the page at all. The product UPC is appended as a hash. Problem is that when a user clicks the back button, it doesn't work. A user currently has to rely on breadcrumbs to go back.

My solution was to use a window on hash change function, which works but obviously forces the page to reload when going forward. Kind of defeats the purpose of AJAX. Is there a better way to navigate to the last item on the page if a user clicks the back button by grabbing its hash value rather than doing what I am currently using below?

$(window).on('hashchange', function() {
  var hash = window.location.hash;
  var fullURL = window.location.href = "http://www.test.com/product-categories/test.php" + hash;
  if (fullURL) {
      location.reload();
  } 
});
Tom
  • 305
  • 1
  • 3
  • 15
  • 1
    Use History.pushState API. This way you can keep your content in History and user can travel through back & forth - https://code.tutsplus.com/tutorials/an-introduction-to-the-html5-history-api--cms-22160 – serdar.sanri Apr 06 '17 at 20:08
  • 1
    i think http://sammyjs.org/ would be useful for this – ryan Apr 06 '17 at 20:08
  • these both look promising thank you! – Tom Apr 06 '17 at 20:11

1 Answers1

1

Here is how you can do it with History API

function loadProduct(productid, reload){
   $.ajax({
     ... 
     ...
     data: {productId : productid},
     success:function(){
       if(!reload) {
            History.pushState('productName', { productId : productid }, '#' + productId)
       }
     }
   })
}

 $(product).on('click', function(){
    loadProduct( productId , true )
 });
 $(window).on('popstate', function(){
   loadProduct( e.state.productId, false );
 });

This way you will store product id each time user clicks on a product. and when they go back & forth, it will get the stored product id and will reload it

serdar.sanri
  • 2,217
  • 1
  • 17
  • 21
  • thank you! this looks like it will work perfectly for my needs. appreciate it! – Tom Apr 06 '17 at 20:22
  • how would you use this plugin with JSON? is that possible as well? – Tom Apr 07 '17 at 13:52
  • yes, you can store json data in pushState. There is no limit mentioned in any browser's documentation though as it mentioned here http://stackoverflow.com/a/22214096/1911146 – serdar.sanri Apr 07 '17 at 14:06