Jump to content

InnerHTML not receiving variable when function is called on it. (ajax)


Omirion

Recommended Posts

Ok it's sort of a strange problem so bare with me i basically have this ajax call.

 

this.getData = function (file) {
			http = new XMLHttpRequest();
			http.onreadystatechange = function () {
				if (http.readyState == 4 && http.status == 200) {
					var temp = http.responseText;
					return temp;
				}
			}
			http.open('GET', file, true);
			http.send();
		}

It's part of an object called stream. So when i do this.

window.onload = function () {
		var str = new stream();
		document.getElementById('test').innerHTML = str.getData('test.php')
	}

 

The updated element gets an undefined variable.

 

But if a alert the value from inside the function like so.

var temp = http.responseText;
alert(temp);

 

The variable is set...

I can't understand why it would do that.

 

The php script on the other end is just.

 

<?php
echo rend()
?>

I got to the bottom of it.

 

It's because the assignment of the variable in the onload event actually happens before the request is sent or before it is received  either way the variable is empty on assignment.

 

If a place a timeout on the assignment it works.

 

Anyone know of a more aesthetic way of handling this?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.