0

Hai

i'm new to the ajax please help me to resolve this my problem. Following is the ajax code i'm using. If the ready state is 4 i'm assinging 1 to 'y'. after that if i'm going to print y it's showing undefined. what is the wrong with my code.

Thanks in advance

var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.responseText == "Wrong")
{
y = 1;
}
}
}
xmlHttp.open("GET", "/inc/test.php?temp="+temp, true);
xmlHttp.send(null);

var xmlHttp = getXMLHttp();
			xmlHttp.onreadystatechange = function()
			{
				if(xmlHttp.readyState == 4)
				{
					if(xmlHttp.responseText)
					{ 
						y = 1;
					}
				}
			}
			xmlHttp.open("GET", "/inc/test.php?captcha="+temp, true); 
			xmlHttp.send(null);
                        alert(y);

Edited by aitha: n/a

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by aitha
0

It's a dual question of variable "scope" and runtime asychronicity.

Variable Scope
y in your statement y = 1; is in a different scope from the y in alert(y); . To ensure that both y's are the same y, declare it with var y; in the global namespace (ie not inside a function).

Asychronicity
Despite the order of the statements, alert(y); will execute before y = 1; . That's because the code is performing AJAX. The anonymous onreadystatechange function is not executed immediately at the point where it is defined. Javascript waits until xmlHttp.readyState == 4 before executing the function. That is an example of asychronicity.

Either of the following should work:

var y;
  var xmlHttp = getXMLHttp();
  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4) {
      if(xmlHttp.responseText) {
        y = 1;
        alert(y);
      }
    }
  }
  xmlHttp.open("GET", "/inc/test.php?captcha="+temp, true);
  xmlHttp.send(null);
var xmlHttp = getXMLHttp();
  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4) {
      if(xmlHttp.responseText) {
        var y = 1;
        alert(y);
      }
    }
  }
  xmlHttp.open("GET", "/inc/test.php?captcha="+temp, true);
  xmlHttp.send(null);

Airshow

Edited by Airshow: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.