20 October 2013

Preserving The dynamically Added Content When Revisited Using Back Button

The problem with back button is, When user clicks on the back button to revisit the page, the browser displays the cached page. When it displays the cached page all the content that we added dynamically to the html page using javascript on the client side will be lost. For example look at the following html.

HTML with dynamic content added on client side using javascript:-
<html>
   <head>
     <script>
       function insert(){
          var str="<div>Enter The Value :<input type='text' name='magic'></div>";
           document.getElementById("sky").innerHTML=str;
       }
     </script>
   </head>
   <body>
     <form action="xxx" method="post">
       Name : <input type="text"  name="name" >
       <div id="sky" onclick="insert()">Press here for magic</div>
       <input type="submit" value="submit" >
     </form>
   <body>
</html>

In the above html when the user clicks on the magic “div” the insert function gets fired and it inserts a div which contains some elements into the magic div. Now after this the user moved to the next page and he clicked the browsers back button to revisit this page. When he comes to this page again using browsers back button all the content that we added to this html using javascript will be lost as they are added at runtime. So to prevent this we can use few efficient techniques.

I mean if you want to restore the page when user revisited using browsers back button  with all the dynamic content then we can use Ajax or Cookies or Hidden fields to solve this problem. which technique to use will be based on your requirement. To restore the content fire ajax or javascript function on Page load. Even when the browser is loading the html from the cache the loading events gets fired so you can use any method to store the state and restore them using javascript or ajax by calling the functions when onload event gets fired.

Using Ajax to Deal this problem:-
Use the command pattern so that each method which modifies the page's UI by adding controls also invokes an AJAX method to push the method invoked (textual Javascript representation) onto a queue stored in the server's session.

After body onLoad completes, use an AJAX method to query the server's session for a command queue for the page the user is on. If one is retrieved, just eval each member of the queue to rebuild the page's UI in the same order the user did it.

For complete thread on how to solve using Ajax please follow the thread below:-
http://stackoverflow.com/questions/1724739/back-button-handle-a-dynamic-form/1724780#1724780



No comments: