ajax no worky
August 24, 2005 11:25 AM Subscribe
I'm having an Ajax (Javascript) problem... it only updates once.
I wrote the following code in an effort to learn how this newfangled Ajax stuff works, but it only tells you the time once -- it refuses to update. What am I doing wrong?
Code:
I wrote the following code in an effort to learn how this newfangled Ajax stuff works, but it only tells you the time once -- it refuses to update. What am I doing wrong?
Code:
var http; function createRequest() { var xmlhttp; if (navigator.appName == "Microsoft Internet Explorer") { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } else { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } window.onload = function() { http = createRequest(); http.onreadystatechange = writeOut; getTime(); } function getTime() { http.open("get", "time?hash=" + Math.random()); http.send(null); setTimeout("getTime()", 1000); } function writeOut() { if (http.readyState == 4) { document.getElementById('here').innerHTML = http.responseText; } }
Response by poster: Makes sense as a solution, but it doesn't seem to make any difference.
posted by reklaw at 11:59 AM on August 24, 2005
posted by reklaw at 11:59 AM on August 24, 2005
Response by poster: Aha, solved it.
http = createRequest();
needed to be
if (!http) { http = createRequest(); }
My problem just came from sucking at Javascript.
posted by reklaw at 12:28 PM on August 24, 2005
http = createRequest();
needed to be
if (!http) { http = createRequest(); }
My problem just came from sucking at Javascript.
posted by reklaw at 12:28 PM on August 24, 2005
Best answer: Also, instead of putting a setTimeout() that calls setTime() from inside of setTime(), why not just call a setInterval("setTime()",1000); in your anonymous onload.
Recursive code should be avoided when possible.
posted by furtive at 2:06 PM on August 24, 2005
Recursive code should be avoided when possible.
posted by furtive at 2:06 PM on August 24, 2005
This thread is closed to new comments.
The first thing I'd try would be moving that setTimeout into your writeOut function, inside the if block, so it only gets called after the previous request has succeeded.
posted by ook at 11:43 AM on August 24, 2005