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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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