PDA

View Full Version : Assign Responsetext to Variable


0x001A4
04-23-2009, 05:06 PM
I'm trying to assign responseText to a variable. Here is my code:
var news, len, count;

news = "";
len = 0;
count = 0;

window.onload = function(){
var xmlHttp = getXmlHttp();
var script = "./scripts/getNews.php";

if (xmlHttp != null){
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4){
news = xmlHttp.responseText;
}
}
}
xmlHttp.open("GET", script, true);
xmlHttp.send(null);
alert(news);
len = news.length;
alert(news);
alert(len);
run();
}
The problem is that the first alert will show up empty, the second alert has the value and len is the correct length. If I remove the first alert, len becomes zero and the second alert is blank. I will admit that the second problem is that I don't have a complete grasp of ajax concepts. So the way I'm going about it could be completely backwards.

Basically I call the run() function when the page is done loading and the run() function will display the value on the page. The reason I don't just display it when readyState becomes 4 is because I need to manipulate it in such a way that I can't do it within that if statement.

0x001A4
04-23-2009, 05:46 PM
Well it seems to work if I remove the len = news.length; line and establish the length in my run() function. I'm going to leave it like this for now, but if anyone reads this post and notices something that I'm doing wrong (ie. where I'm calling my run() function) please let me know :D

oesxyl
04-23-2009, 05:51 PM
Well it seems to work if I remove the len = news.length; line and establish the length in my run() function. I'm going to leave it like this for now, but if anyone reads this post and notices something that I'm doing wrong (ie. where I'm calling my run() function) please let me know :D
I'm not sure but I guess that XMLHttpRequest object don't have a 'length' so the script will stop at that line.

best regards

shyam
04-23-2009, 06:18 PM
maybe u should try changing to a synchronous request

xmlHttp.open("GET", script, false);