View Single Post
Old 01-25-2012, 11:52 AM   PM User | #11
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
This is a common mistake. Outside of onreadystatechange the "myvar" variable remains undefined, because this code will be executed BEFORE the request has finished.

Conclusion: Everything you want to do depending on the result of the request has to be (started from) inside the onreadystatechange callback

Code:
var myvar = "";
var http = XMLHttpRequest();
http.open('GET', 'text1.txt', true);
http.onreadystatechange = function() {
   if(http.readyState == 4 && http.status == 200) {
       myvar = http.responseText;
       var tcolor1 = myvar;
       var tcolor2 = "pink";
       var tcolor3 = "blue";
       var tcolor4 = "orange";
       document.getElementById('color1').style.color = tcolor1;
       document.getElementById('color2').style.color = tcolor1;
       document.getElementById('color3').style.color = tcolor1;
       document.getElementById('color4').style.color = tcolor1;
       document.getElementById('color5').style.color = tcolor1;
       document.getElementById('color6').style.color = tcolor1;
       document.getElementById('color7').style.color = tcolor1;
       document.getElementById('color8').style.color = tcolor1;
   }
}
http.send(null);
devnull69 is offline   Reply With Quote