In xmlhttp.onreadystatechange function, how do I pass the name of the ID I want to edit?

StackOverflow https://stackoverflow.com/questions/1425358

  •  07-07-2019
  •  | 
  •  

Question

Here's my code. See the line that is commented out. When the element id (which is a span) is hardcoded, it works. When the id is created by concatenating the variables passed into stateChanged, it does not work. Am I not allowed to pass variables in to stateChanged? What's wrong?

function multiplePassportPoints(id, counter)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="addmorepoints.php"; 
url=url+"?id="+id+"&c="+counter;
url=url+"&sid="+Math.random();

xmlhttp.onreadystatechange=stateChanged(id,counter);
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged(id, counter) 
{
  if (xmlhttp.readyState==4)
  {
    //THIS WORKS (assuming id is 99 and counter is 5:
    //document.getElementById("99_5").innerHTML += xmlhttp.responseText; 

    //BUT I NEED IT TO WORK LIKE THIS:
    document.getElementById(studentID+"_"+counter).innerHTML += xmlhttp.responseText; 
  }
}

Thanks!

Was it helpful?

Solution

You can change the code to this

xmlhttp.onreadystatechange = function () {
        stateChanged(id,counter);
    };    

OTHER TIPS

 <script type="text/javascript">
 var i=1;
 function validate(str)
 { 
 xmlHttp=GetXmlHttpObject()
 var url="checkvalidate.php"
 url=url+"?User9="+str
 xmlHttp.onreadystatechange=stateChanged19 
 xmlHttp.open("GET",url,true)
 xmlHttp.send(null)
 }
function stateChanged19() 
 {  

 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  { 

  document.getElementById("valid"+i)
  .innerHTML=xmlHttp.responseText 
  i=i+1;
   } }
 </script>

A better method which can be called multiple times before the previous call finishes. Notice that if you call multiplePassportPoints twice your previous value of xmlhttp will get overwritten. There are two outcomes:
1- everything works fine when no concurrency occurs (very high possibility),
2- first call never happens (very low possibility but it will happen from time to time and will be very hard to spot and reproduce)

But the following code uses local variable and might (not tested) be safe to call again and again.

function multiplePassportPoints(id, counter) {
  var xmlhttp=GetXmlHttpObject();
  if (xmlhttp==null)
  {
    alert ("Browser does not support HTTP Request");
    return;
  }

  var url="addmorepoints.php"; 
  url=url+"?id="+id+"&c="+counter;
  url=url+"&sid="+Math.random();

  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4) {
      stateChanged(id, data, xmlhttp.responseText);
    }
  };

  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
}

function stateChanged(id, counter,text) 
{
    document.getElementById(id+"_"+counter).innerHTML += text; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top