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:
		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;
			} 

		}
posted by reklaw to Technology (4 answers total)
 
This may or may not be the source of the problem you're seeing... but if your xmlhttprequest call takes longer than a second to return its results, it'll never reach a readyState (since your getTime function keeps resetting it whether the previous call is complete or not.)

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


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


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


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


« Older Whoops we forgot to plan the honeymoon   |   Sedona/Flagstaff recommendations Newer »
This thread is closed to new comments.