How to update page in regular intervals with AJAX

Discussion in 'JavaScript' started by vangelis, Oct 4, 2006.

  1. #1
    Hi all,
    how is it possible to update some elements in a page in timely intervals using AJAX? Do i need to call the XMLHttpRequest within a setInterval or a setTimeout or is there some other way?
     
    vangelis, Oct 4, 2006 IP
  2. frankcow

    frankcow Well-Known Member

    Messages:
    4,859
    Likes Received:
    265
    Best Answers:
    0
    Trophy Points:
    180
    #2
    that is essentially what you need to do
    you can look at the code from the 'spy' tool under fun stuff on this forum
     
    frankcow, Oct 4, 2006 IP
  3. randommouse

    randommouse Peon

    Messages:
    26
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    i recommend using the prototype.js library for AJAX scripting. it makes life easier. then look into the Ajax.PeriodicalUpdater() method for polling at specified intervals. the basic structure of a polling call will look something like this:

    
    <script type="text/javascript" language="javascript" src="http://mydomain/prototype.js"></script>
    <script type="text/javascript" language="javascript">
    <!--
    function startMonitor()
    {
    	var upload_monitor_url = 'http://mydomain/cgi-bin/monitor.cgi';
    	var frequency_value = 1;
    	var decay_value = 2;
    
    	var ajax_upload_monitor = new Ajax.PeriodicalUpdater(
    		{},
    		upload_monitor_url,
    		{
    			'method': 'get',
    			'parameters': null,
    			'frequency': frequency_value,
    			'decay': decay_value,
    			'onSuccess': function(request){updateProgress(request)},
    			'onFailure': function(request){updateFailure(request)}
    		}
    	);
    }
    function updateProgress(req)
    {
    	// update the information on the page that tells we where are at
    
    	$('some_div_id').innerHTML = req.responseText;
    }
    function updateFailure(req)
    {
    	// the monitored process has finished (hopefully successfully)
    
    	$('another_div_id').innerHTML = 'all done!';
    }
    startMonitor();
    // -->
    </script>
    
    Code (markup):
    the updateFailure() method will be called when your monitoring script exits rather than returns a text value when queried.
     
    randommouse, Oct 8, 2006 IP