/ ajax-jquery

Change URL and enable browser back button with AJAX

We all are aware that clicking any link that sends AJAX call doesn't change the url with the href of the link clicked. As the browsers history is not also updated, back button too will not work.

One alternative is to use PJAX that updates the url and browsers history thus enabling back button.

What if we don't what to use PJAX?

There is way of manipulate browsers history to reflect updated url and enable back button. This technique is used by Github in its file browser. When we click on folder in Github repo, the page updates via AJAX and the url is also updated. Thus making it easier to bookmark a page. Also, the page is added to browsers history so the back button works as expected.

To change the browser's URL, call ***pushState()***. The documentation for pushState() can be found [here][1] .

To make back button work with AJAX, catch onpopstate event. This handler is triggered that changes the url when back button is clicked. On this event, send AJAX to location.href . This will update the page.

Code snippet:

 // for changing URL
$(link).live('click', function () {
  history.pushState(null, "", this.href);
  return false;

// for back button

$(window).bind("popstate", function () {

Have fun AJAXing :-)
[1]: https://developer.mozilla.org/en/docs/DOM/Manipulating_the_browser_history