Friday, October 28th, 2005

Ajax: Tackle the Refresh Button

Category: Articles

Eric Pascarello is tackling the browser refresh and its effects on Ajax applications.

The last thing we want is for a user to hit refresh and all of your nice state goes bye-bye.

Eric takes an approach that changes the URL between state changes, allowing a refresh to capture the info:

function makeRequest2(str){
  var loader1 = new net.ContentLoader("testHistory.aspx",finishRequest2,null,"POST","q=" + str);
   window.location.hash = str;

function finishRequest2(){
  document.getElementById("spanId2").innerHTML = this.req.responseText;

  if(window.location.hash.length > 0)

The first thing is we set the hash of the window to the parameter that the server recognizes. (Note: setting the hash does not cause the page to refresh/submit!) If your system is a little more advanced, you will have to figure out a relationship between the server and the client. The other thing we do is add the onload handler to the document so we can look for the hash. If it exists, we remove the # and send the XMLHttpRequest to the server. The request then fills in the information on the page. The user may notice the data swap depending on the lenght of time for the response. It is a rather simple solution with a lot of work that needs to be done if you have a complex request.

Posted by Dion Almaer at 3:16 am

4.6 rating from 118 votes


Comments feed

This has been my single biggest frustration with my one-week switch from Safari to Firefox – Firefox forgets state, while Safari “just works”.

Comment by Michal Migurski — October 28, 2005

I’ve tried experimenting with the location hash in javascript and the one quirk I found was that there’s no browser event I could find to capture if the user hits the back/forward buttons and navigates between different hashes.

Comment by Joe Tan — October 28, 2005

Just use hidden form fields for state.

Always keep all state there if it needs to be remembered. It works great in my experience so far (across simple refresh, backward, and forward).

Comment by Tom — October 28, 2005

My only comment to the textbox solution is: But can you bookmark a textbox? You can bookmark the hash.

Comment by Eric Pascarello — November 1, 2005

From what I understand the theory is this:
You specify a hash each time a function is called, and then that automatically works right? We just need to make a random hash for each call. Am i Right ?

Comment by exe — January 6, 2006

what kind of programing need

Comment by cicekclub — April 2, 2006

More advanced and detailed article you can find right here:

Comment by Solid — August 28, 2006

Leave a comment

You must be logged in to post a comment.