Jump to content

[SOLVED] Is it possible to set a global variable inside the onreadystatechange-function


mrzoom

Recommended Posts

function a()
{
  // This function is called by an onclick or something.

  var myXmlDoc = getXmlDoc();

}

function getXmlDoc()
{
  var myXmlDoc;

  // This function is suppose to return the xmldoc, that is generated in a php-file.
  
  //So here i make the ajax call to the php file. But i skip all the standard code, it's just the onreadystatechange-function that is importent to show you here...

  ...
  xmlHttp.onreadystatechange = function()
  {	
    if(xmlHttp.readyState == 4)
    {
    	// How do i store my xmlHttp.responseXML in myXmlDoc so it can be returned at the and of the getXmlDoc-function?
    }
  }
  ...
  
  return myXmlDoc;
}

It doesn't work like that. AJAX is asynchronous, mean it doesn't wait for the readystatechange. So, getXmlDoc() will finish and return to a() before onreadystatechange() is even executed. Anything you want to do with myXmlDoc should be inside the onreadystatechange() function.

 

But, you can declare a global variable like so:

var myXmlDoc; //This makes a global variable

function a()
{
  getXmlDoc();
}

function getXmlDoc()
{
  //var myXmlDoc; Remove the variable declaration
  xmlHttp.onreadystatechange = function()
  {   
    if(xmlHttp.readyState == 4)
    {
      myXmlDoc = xmlHttp.responseXML;
    }
  }
  return;
}

Ah.. I see...

 

I used somthing like this to solve it instead:

 

function getXmlDoc()
{
  try //Internet Explorer
  {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  }
  catch(e)
  {
    try //Firefox, Mozilla, Opera, etc.
    {
      xmlDoc = document.implementation.createDocument("","",null);
    }
    catch(e)
    {
      alert(e.message);
      return;
    }
  }
  xmlDoc.async=false;
  xmlDoc.load("/test.php);
  
  return xmlDoc;
}

Archived

This topic is now archived and is closed to further replies.

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