views:

304

answers:

1

I have an AJAXed page, but I also offer a query string to the user so that he/she may type in the query string to the url to see the same page again. (Think google maps and its "share link" feature).

When the AJAX request occurs I update the query string presented to the user, but the actual URL does not change. The problem is, if a user refreshes the page, all the DOM elements created from AJAX disappear.

What I want to do is have javascript capture the refresh event, and instead of refreshing the page, redirect the user to the page plus the query string.

ie if query string is: ?data=blah&stuff=bleh

then instead of refreshing page back to www.example.com, refreshing would lead the user to www.example.com/?data=blah&stuff=bleh

+1  A: 

You can't change the querystring...without the browser actually leaving the page and fetching a new one (kind of killing the point of AJAX).

You can go to a hash though, like this: www.example.com/#data=blah&stuff=bleh

In your script just set the window.location.hash, e.g.:

window.location.hash = "data=blah$stuff=bleh";

When your page loads, you'll need to actually use the hash...for example: using it as the data parameter to do the same AJAX call you made before.

Nick Craver
I was actually thinking of having the page ACTUALLY redirect to the query string url on page refreshes but leaving the URL the same in other cases. However, your technique is probably a better solution, I'll try it out!
Razor Storm
I tried it and it works wonderfully. However, I just realized one problem. Since hashes are meant to be used for inpage navigation, entering a hashed url into the location bar doesn't actually cause the page to refresh. Is there a way to force a refresh when javascript detects this change?
Razor Storm
@Razor - I'm curious...if you *want* the page to refresh, why are you using AJAX?
Nick Craver
@Nick, no I don't want the page to refresh when the AJAX request occurs. What I mean is this. When the AJAX request occurs, the page does not refresh, then it changes the url to www.example.com/#data=blah. This part works perfectly.\nNow say your friend sends you a link "www.example.com/#data=bloh". And you put this into your url bar and press enter. If you are already on www.example.com, your page won't actually go to your friend's page, and instead will simply stay at the same page you were previously on since hashes doesn't cause a page refresh.
Razor Storm
@Razor - Ah in that case yes there is an `onhashchange` event...but it's not cross-browser supported. But...there's a plugin to normalize it so it works everywhere: http://benalman.com/projects/jquery-hashchange-plugin/
Nick Craver
Thanks! This is exactly what I was looking for.
Razor Storm