views:

1506

answers:

2

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!

+2  A: 

You can change the code to this

xmlhttp.onreadystatechange = function () {
        stateChanged(id,counter);
    };
rahul
rock on! it works! thanks.
Jen
+1. But I wish you would have explained that `xmlhttp.onreadystatechange=stateChanged(id,counter);` was actually invoking `stateChanged(id,counter)` and assigning the return value to `onreadystatechange` rather than assigning the function itself.
Grant Wagner
A: 

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

related questions