views:

210

answers:

3

hi, i have the code below but getElementById(setID) not working for me, i know it catches the id because alert(setID) working.

any idea?

function getdata(file, aID){
req = xmlHttpRequestHandler.createXmlHttpRequest();
req.onreadystatechange = Response;
req.open("GET", file, true);
req.send(null);
setID = aID;
}

function Response() { 
    var ready, status;
    try {
        ready = req.readyState;
        status = req.status;
    }
    catch(e) {}
    if (ready == 4 && status == 200) {
          document.getElementById("data").innerHTML = req.responseText;
    }

   document.getElementById(setID).className = "someclass";
}


<div class="msg" id="someid">
<a href="javascript:getdata('data.php', 'someid')">somelink</a>
</div>
+1  A: 

If

document.getElementById("data")

doesn't work, this has one of the following reasons in 99% of all cases:

  • The element does not exist or exist anymore

  • There are more than one element with the id data

This happens often when the AJAX call introduces HTML code that also contains an element with the same ID.

Pekka
+4  A: 

Either use setID as a global variable or pass it to the callback function.

function getdata(file, aID)
{
    req = xmlHttpRequestHandler.createXmlHttpRequest();
    setID = aID;
    req.onreadystatechange = function() {Response(setID);};
    req.open("GET", file, true);
    req.send(null);
}

function Response(setID) 
rahul
tried that but still not working ( document.getElementById(setID) is null)
JQman
Are you sure your rendered document has an element whose id is the alue of setID? If the element is inside a naming container then you have to use ClientID to get the id of that particular element.
rahul
ok that finally worked ;)
JQman
the setID is globally defined. and the script is OK, i found no problem in this script.
+1  A: 

Are you making your setID variable global? If not then try this:

var setID = null; // we set this here because it is referenced in functions

function getdata(file, aID){
req = xmlHttpRequestHandler.createXmlHttpRequest();
req.onreadystatechange = Response;
req.open("GET", file, true);
req.send(null);
setID = aID;
}

function Response() { 
    var ready, status;
    try {
        ready = req.readyState;
        status = req.status;
    }
    catch(e) {}
    if (ready == 4 && status == 200) {
          document.getElementById("data").innerHTML = req.responseText;
    }

   document.getElementById(setID).className = "someclass";
}
Sarfraz