Page 1 of 1

input for stateChanged()

Posted: Tue Apr 13, 2010 11:25 pm
by m2babaey
Hi
When I want to define input variable for stateChanged, my code doesn't work
I don't want to define lots of stateChanged functions. How can I fix it?
This code doesn't work:

Code: Select all

function loadrealms(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  }
var url="ajaxphp.php";
url=url+"?action=loadrealms&region="+str;
xmlhttp.onreadystatechange=stateChanged('realmoptions');
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged(div_id)
{
if (xmlhttp.readyState==4)
  {
  document.getElementById(div_id).innerHTML=xmlhttp.responseText;
  }
}
But this code works fine:

Code: Select all

function loadrealms(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  }
var url="ajaxphp.php";
url=url+"?action=loadrealms&region="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  document.getElementById("realmoptions").innerHTML=xmlhttp.responseText;
  }
} 

Re: input for stateChanged()

Posted: Wed Apr 14, 2010 5:36 pm
by kaszu
Because stateChanged('realmoptions'); is a call to function, which returns nothing. Basically that's the same as

Code: Select all

xmlhttp.onreadystatechange=undefined;
Workaround:

Code: Select all

function stateChanged(div_id)
{
  //returns function, which will be as onreadystatechange event handler
  return function () {
    if (xmlhttp.readyState==4)
    {
      document.getElementById(div_id).innerHTML=xmlhttp.responseText;
    }
  }
}