Hi,
with Mozila everything work, but with IE didn't work. Page didn't reload.
What's wrong?

<html>
<head>
<script type="text/javascript">
 setInterval("sendRequest()", 1000*2);
function createRequestObject() { 
   var req; 
   if(window.XMLHttpRequest){ 
      // IE 7, Firefox, Safari, Opera... 
      req = new XMLHttpRequest(); 
   } else if(window.ActiveXObject) { 
      // Internet Explorer 6, 5 
      req = new ActiveXObject("Microsoft.XMLHTTP"); 
   } else { 
      
      alert('Problem creating the XMLHttpRequest object'); 
   } 
   return req; 
} 

var http = createRequestObject();

function sendRequest() { 
   http.open('GET', 'select.php', true);
   http.onreadystatechange = handleResponse;
   http.send(null);
}

function handleResponse() { 
   if(http.readyState == 4 && http.status == 200){ 
      var response = http.responseText; 
      if(response) 
      { 
         document.getElementById('text').innerHTML = response; 
      } 
   } 
}

</script>
</head>
<body>
<div id="text"></div>
</body>
</html>

try to put those interval's with an onload event:

window.onload = function() {
   int = setInterval("sendRequest()", 2000);
};

Lolalola,

As far as I can tell, an IE XMLHTTP request is a one-shot affair whereas in Moz it will work many times over.

As such, there is little point in making your "http" global. It can (and should I believe) be declared within sendRequest() with var http = createRequestObject(); .

You will then need to change the way that handleResponse is called (attach an anonymous function which calls handleResponse with http.responseText as its argument). It is also advisable to attach this listener before http.open, not after.

This is a pretty standard pattern, of which you should find many examples here on Daniweb and elsewhere.

Hope this helps.

Airshow

It's totally a mistake to use global variable instance of XMLHttpRequest,when there will be multiple requests at one time.
A simple call to setInterval will not satisfy you need.
Because your XMLHttpRequest is asynchronous,when the previous request is pending(say,waiting response from your server),another
request is being issued,and because you use global var,the first request is 'flushed' by its successor!
Below code assumes the use of jQuery framework.
and a small code snippet(the Polling class) from http://blog.viscent.info/?p=7

function handleResponse(data){
    $('#s').html(data);
    task.interval=500;
    request();

}
function doRequest(){
    $.get('time.php?id='+ Math.random(),handleResponse);
}

var polling=new Polling();
var task={handler:doRequest,count:1,interval:1};
function request(){
    polling.exec(task);

}
$(document).ready(function(){
    request();
});

Edited 3 Years Ago by mike_2000_17: Fixed formatting

This article has been dead for over six months. Start a new discussion instead.