0

I am using pagination with ajax. If user click on 3rd then I am opening third page using ajax.

If from that page, I go to another page & click on browser back button then page 3rd not opening. It is opening 1st page.

So how can I open 3rd page, if user click on back button

Bhaurao Birajdar
  • 1,437
  • 11
  • 15
  • Possible duplicate of [How to keep the browser history in sync when using Ajax?](http://stackoverflow.com/questions/29886/how-to-keep-the-browser-history-in-sync-when-using-ajax) – Dekel Aug 07 '16 at 12:29
  • Have you see my answer? What do you say? – Mosh Feu Aug 08 '16 at 11:02

2 Answers2

0

You can use hash (or pushState method in modern browsers) to "save" the last pagination state. When you load the data, take the page from the hash.

Here is primitive sample. You can see that if you click on the links to move to another page, then you turn back (using back button or whatever) it's present the previews items.

How it works?

Whenever you click on the links, let's say the first link, which his href attribute is #1 the event hashchange was fired. Now, you can read the value of the hash by using location.hash (the replace method uses for remove the # symbol). Now, if you click on the second link then click back the hashchage event fired again and so on..

// set data
var data = [],
    numOfPages = 5;

for (var i = 0; i < numOfPages; i++) {
  data.push([1 + '' + i, 2 + '' + i, 3 + '' + i, 4 + '' + i, 5 + '' + i]);
}

// paging method
var list = document.querySelector('ul');
function getPage(pageNum) {
  !pageNum && (pageNum = 0);
  var html = '';
  for (var i = 0; i < data[pageNum].length; i++) {
    html += ('<li>' + data[pageNum][i] + '</li>');
  }
  list.innerHTML = html;
}

getPage();

// generate pageing buttons
var paging = document.querySelector('#paging'),
    pagingHTML = '';

for (var i = 0; i < data.length; i++) {
  pagingHTML += ('<a href="#' + i +'">' + i + '</a>');
}

paging.innerHTML = pagingHTML;

// listen to changes in the hash
window.addEventListener('hashchange', function() {
  var pageIndex = location.hash.replace('#', '');
  getPage(pageIndex);
});
a {
  display:inline-block;
  margin-left: 10px;
}
<ul></ul>
<div id="paging"></div>
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
0

I have solved this issue by using html5 Local Storage.

When using click on any page then that page no, I am storing in local storage. So if user go to another page & click on back button, then I am getting last page no that he clicked & I am getting those records.

So by use Local Storage, problem is solved.

Bhaurao Birajdar
  • 1,437
  • 11
  • 15