Question

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>
Was it helpful?

Solution

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) 

OTHER TIPS

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.

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";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top