Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: ajax-refresh-page

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: ajax-refresh-page
Showing posts with label ajax-refresh-page. Show all posts
Showing posts with label ajax-refresh-page. Show all posts

JAVA SCRIPT - Using a Timer to Automatically Update the Page with Fresh Data

Using a Timer to Automatically Update the Page with Fresh Data


Problem

You want to display entries from a file, but the file is updated frequently. 

Solution

Use Ajax and a timer to periodically check the file for new values and update the display accordingly. The Ajax we use is no different than any other Ajax request. We’ll use a GET, because we’re retrieving data.

 We put together the request, attach a function to the onreadysta techange event handler, and send the request: 


var xmlhttp;
// prepare and send XHR request
function populateList() {
 var url = 'text.txt'; // change to full url to prevent caching problems
 xmlhttp.open('GET', url, true);
 xmlhttp.onreadystatechange = processResponse;
 xmlhttp.send(null);
}

In the code that processes the response, we just place the new text into a new unordered list item and append it to an existing ul element:

// process return
function processResponse() {
 if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
 var li = document.createElement("li");
 var txt = document.createTextNode(xmlhttp.responseText);
 li.appendChild(txt);
 document.getElementById("update").appendChild(li);
 setTimeout(populateList,15000);
 } else if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
 console.log(xmlhttp.responseText);
 }
}

The new part is the addition of the setTimeout() in the code. It triggers the entire process again in 15 seconds.The process is started by creating the xmlHttpRequest object in the Window load event handler, and then calling populateList() the first time:

window.onload=function() {
 xmlhttp = new XMLHttpRequest();
 populateList();
}


EXPLAIN

The fact that we’re doing a direct request on a static text file might be new, but remember that a GET request is more or less the same as the requests we put into the location bar of our browsers. If something works in the browser, it should successfully return in an Ajax GET request…within reason. 

The key to using timers with Ajax calls is to make sure that the last call is completed before making the next. By adding the call to setTimeout() at the end of the Ajax call, we trigger the timer when we know an outstanding request isn’t being processed. We can also put in a check for the request status, and cancel the timer event altogether if we’re concerned about hitting a failing service, over and over again. When I ran the application that included the solution code, 

I changed the text file by using the Unix echo command: 


$ echo "This is working" > text.txt