How to schedule ajax calls every N seconds?

If I want the whole page to load every N seconds, I would add something like this in the HTML: meta http-equiv="refresh" content="5"

Is there a standard practice for doing the same thing for AJAX calls? I want the AJAX chart to call every 10 seconds to refresh parts of the page without refreshing the whole page. It would be even better if I could schedule several AJAX calls at different times, as some parts of the page may need to be updated more often than others.

TIA

+6
javascript ajax
source share
4 answers

You can use setTimeout or setInterval (the latter is probably best suited for what you want to do).

 setInterval(makeRequest, (10 * 1000)); 

... where makeRequest is a function that reloads some content through AJAX.

+11
source share
 function proxy() { /* implement call to your Ajax method */ } setInterval( proxy, 1000 ); // last arg is in milliseconds 
+4
source share
 You can use serInterval method of javascript: Just write down the lines at the bottom of your page: <script> window.setInterval(function(){ ajaxCallFunction(); //calling every 5 seconds }, 5000); function ajaxCallFunction(){ //this function uses ajax to interact with the server } <script> 
+1
source share

I assume that a servlet with a url is configured in web.xml. / UpdateCount is configured to provide dynamic data / content, and there is a div element in the countStatDiv element . jsp page.

The following code updates / updates the contents of countStatDiv every 30 seconds using the GET method, and the value of the second variable can be changed as necessary:

  <script> var request; var seconds=30; function getRequestObject(){ setInterval(function() {sendRequest();},seconds*1000); if (window.ActiveXObject){ return (new ActiveXObject("Microsoft.XMLHTTP")); } else if (window.XMLHttpRequest){ return(new XMLHttpRequest()); } else { return (null); } } function sendRequest(){ request = getRequestObject(); request.onreadystatechange = handleResponse; request.open("GET", "../UpdateCount", true); request.send(null); } function handleResponse(){ if((request.readyState == 4)&amp;&amp;(request.status == 200)){ var serverResponse = request.responseText; var statCtrl=document.getElementById("countStatDiv"); statCtrl.innerHTML=serverResponse; } } </script> 
0
source share

All Articles