Modify Address Bar URL in AJAX App to Match Current State

Look at sites like book.cakephp.org. This site changes the URL without using the hash and use AJAX. I'm not sure how it does it exactly but I've been trying to figure it out. If anyone knows, let me know.

Also github.com when looking at a navigating within a certain project.


The way to do this is to manipulate location.hash when AJAX updates result in a state change that you'd like to have a discrete URL. For example, if your page's url is:

http://example.com/

If a client side function executed this code:

// AJAX code to display the "foo" state goes here.

location.hash = 'foo';

Then, the URL displayed in the browser would be updated to:

http://example.com/#foo

This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states.

With this mechanism in place, you'll then need to parse out the hash portion of the URL on the client side using JavaScript to create and display the appropriate initial state, as fragment identifiers (the part after the #) are not sent to the server.

Ben Alman's hashchange plugin makes the latter a breeze if you're using jQuery.