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()
?>

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.