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);

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

thanks for your replay

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.