Modify Address Bar URL in AJAX App to Match Current State

jasonjwwilliams picture jasonjwwilliams · Aug 4, 2008 · Viewed 73.5k times · Source

I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state.

How are people handling maintaining RESTfulness in AJAX apps?

Answer

Dave Ward picture Dave Ward · Aug 4, 2008

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.