Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify Address Bar URL in AJAX App to Match Current State

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.


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.


It is unlikely the writer wants to reload or redirect his visitor when using Ajax. But why not use HTML5's pushState/replaceState?

You'll be able to modify the addressbar as much as you like. Get natural looking urls, with AJAX.

Check out the code on my latest project: http://iesus.se/


This is similar to what Kevin said. You can have your client state as some javascript object, and when you want to save the state, you serialize the object (using JSON and base64 encoding). You can then set the fragment of the href to this string.

var encodedState = base64(json(state));
var newLocation = oldLocationWithoutFragment + "#" + encodedState;

document.location = newLocation; // adds new entry in browser history
document.location.replace(newLocation); // replaces current entry in browser history

The first way will treat the new state as a new location (so the back button will take them to the previous location). The latter does not.


SWFAddress works in Flash & Javascript projects and lets you create bookmarkable URLs (using the hash method mentioned above) as well as giving you back-button support.

http://www.asual.com/swfaddress/