Code to auto-refresh part of jsp / html page (div area) using ajax and jQuery in a interval

Here lets us see   how to   refresh  the part of the web page (that is div area in a JSP)  automatically in a regular interval  using ajax  with jQuery and without jQuery.  Refreshing the part of the page means , the request is sent to the server and the response from   the server is updated in the specified area.

1. Using Ajax  with jQuery : 

                With jQuery , you need to write with very few lines of code.  The following code sends the request to server automatically  in every 10 seconds, the result in html is updated in the div area  without reloading the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">


var url = 'servlet/util.GetDisplayData'

$(document).ready(function() {

$.ajaxSetup({ cache: false }); 

setInterval(function() {$("#displayarea").load(url); }, 10000);

});

</script>  

In the above code , load command loads data from the server and place the returned HTML into the  selected element.
The load command has the syntax of

  load( url, [data], [callback] )
url – to specify the url to load
data – To sepecify  a set of querystring  in the form of  Object / Map (key/value pairs)   to  send along with the request. This is optional.
callback-  to specify the  name of a function to be executed after the load() method is completed. This is also optional

By Default,  GET request will be performed.  – but if you pass in any extra parameters in the form of an Object/Map (key/value pairs) then a POST  request will be performed. Extra parameters passed as a string will still use a GET request.

To prevent caching by the browser :

                 ajaxSetup({ cache: false } :  By default ,  the browser may cache the request and you may get the same result every time. To prevent this, you can use the command $ajaxSetup({ cache: false } that  does not allow the browser to cache  all future AJAX requests .  This  allows  to retrieve the latest version of an HTML page.  To make use of the cached results, , set cache to true.

2.  Using Ajax  without  jQuery:

<script>


var httpRequest = false;

var url = 'servlet/util.GetDisplayData';

window.onload = hrObject;

function hrObject() {

     if (window.XMLHttpRequest) {

        httpRequest = new XMLHttpRequest();

     }

     else {

        if (window.ActiveXObject) {

           try {

              httpRequest = new ActiveXObject ("Microsoft.XMLHTTP");

           }

           catch (e) { }

        }

     }



getData();

}



function getData() {

     httpRequest.open("GET", url, true);

     httpRequest.onreadystatechange = showData;

     httpRequest.send(null);

     setTimeout("getData()", 10000);

}



function showData() {



     if (httpRequest.readyState == 4) {

        if (httpRequest.status == 200) {

               var ele=document.getElementById("displayarea");

               ele.innerHTML=httpRequest.responseText;

         }

        else {

           alert("Error with loading datan"+ httpRequest.status +":"+ httpRequest.statusText);

        }

     }

}

</script> 

To disable caching when you use the above code ,you can add the below line in the server side code to get  data from the database
 responseObj.setHeader(“Cache-Control”, “no-cache”);

The above line of code tells the browser not to cache the content

The server side  java code  to get  data and return html  is as follows

public class GetDisplayData extends HttpServlet{

 protected void doGet(HttpServletRequest requestObj, HttpServletResponse responseObj)    throws IOException , ServletException

 {

 responseObj.setContentType("text/xml");

     //responseObj.setHeader("Cache-Control", "no-cache");

     PrintWriter writer = responseObj.getWriter();

    

   List displayData = null;

    try {

            DispDAO dispDao = new DispDAO();  // Gets the data from the database and stores in a list

                         displayData = dispDao.getDisplayData();

     

    }catch(Exception e) { }

                                   DispForm df=new DispForm();

       Iterator it =displayData.iterator();

    int id=0;

    String html="";

      html="<Table border=1>";

      while(it.hasNext())

      {

          df=(DispForm)displayData.get(id);

       html=html+"<tr border=1><td>";

       html=html+df.getAirline();

          html=html+"</td><td>";

          html=html+df.getFlightNo();

       html=html+"</td><td>";

           html=html+df.getDestination();

       html=html+"</td><td>";

           html=html+df.getS_time();

       html=html+"</td><td>";

           html=html+df.getEtd();

       html=html+"</td><td>";

           html=html+df.getStatus();

       html=html+"</td></tr>";

       id++;  

     it.next();

      }

                                html=html+"</Table>";

      writer.println(html);

      writer.close();                   
     

    }

 } 

The JSP page code (partly) that contains displayarea (div)  is given below .

<div id="td" align="center">


<table border 2>


<tr>


<td colspan=6 align="center"> Display Board</td>

</tr>


<tr>


<td> Airline</td><td> Flight</td> <td> Destination</td> <td> Scheduled</td> <td> ETD</td> <td> Status</td>

</tr>


</table>;

</div>

<div id="displayarea" align="center">

 </div> 

The data retrieved from the server is updated in the div area.

Note : If you add the line  responseObj.setHeader(“Cache-Control”, “no-cache”)    in the server side code , no need to set  cache false (i.e.  $.ajaxSetup({ cache: false }); )   in the javascript code using Ajax  with jQuery

For running the above code , I have created table with necessary fields  for displaying flight schedules. I got the below output , and the div area got refreshed with the data from the database in every 10 seconds.

You may also like

Leave a Reply