Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

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



Preventing Caching of Ajax Requests

Normally when we use Ajax calls using get method the Ajax request will be cached in the browser’s history and the html pages are cached in the browser’s cache. So the problem with this is, when user clicks on the back button of the browser to return to previous page which have some ajax calls then the calls gets fired but the response comes from the cache. It does not hit the server. If we want to prevent the caching we have to make every request unique by adding a request parameter with some unique value.

The following technique shows how to make request unique:- 

var nocache = new Date().getTime(); 
var path = 'http://hostname.domain.tld/api/somejsonapi/?cache=' + nocache;

Now use the path as your url so that the request becomes unique every time and will not return the cached response. 

If using Ajax calls with get is not mandatory then use Ajax with post method so that the ajax requests and responses are not cached. Post method prevents caching in Ajax.

21 June 2013

Common problem that developers face with Ajax


On so many web sites when ajax is being used to update part of the page sometimes we see 404 server response page which is the ugly part. This is due to lack of proper knowledge of developers on Ajax.

Solution:-

The ideal solution would be to do nothing if the response from the server is not ok. To do this we should check the Ajax request status. if the Ajax request status is 200 that mean the server response is proper, if not then there is a problem. So do nothing when there is a problem.

The following is the code for complete Ajax call:-


function getHTTPObject() {
             if (typeof XMLHttpRequest != 'undefined') {
                        return new XMLHttpRequest();
               }
             try {
                          return new ActiveXObject("Msxml2.XMLHTTP");
              } catch (e) {
                        try {
                                        return new ActiveXObject("Microsoft.XMLHTTP");
                          } catch (e) {}
                 }
                return false;
 }




 <script type="text/javascript">      
   function getSearchStudents(){
                document.getElementById("noStudent").style.visibility = "hidden";
                var userString=document.getElementById("userString").value;
                var http=getHTTPObject();
                 http.open("GET", "searchStudent.do?userString="+userString, true);    
                 http.onreadystatechange = function() {
                              if (http.readyState == 4 && http.status == 200) {
                                          document.getElementById("container").innerHTML=http.responseText;
                                          if(http.responseText=="")
                                                      document.getElementById("noStudent").style.visibility = "visible";
                                          if(http.responseText.length==2)
                                                      document.getElementById("noStudent").style.visibility = "visible";
                                  }
                     }
                    http.send("");    
   }  
  </script>

One good thing that developer needs to know is the states of the Ajax request. There are four states. The "readyState" property can hold four values that is 0,1,2,3,4.

0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready