i have javascript code that does these things in a loop
- create a
div
element,append it to thedom
and get its reference - pass this reference to a function that makes an ajax
post
request - set the response of the ajax request to the
innerHTML
of the passed element reference
here is the code
window.onload = function () {
var categories = document.getElementById('categories').children;
for (i = 0; i < categories.length; i++) {
var link = categories[i].children[1].children[0].attributes['href'].nodeValue;
var div = document.createElement('div');
div.className = "books";
div.style.display = "none";
categories[i].appendChild(div);
getLinks(link, div);
}
}
function getLinks(url, div) {
xhr = new XMLHttpRequest();
xhr.open('POST', 'ebook_catg.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
url = encodeURIComponent(url)
var post = "url=" + url;
xhr.node=div; //in response to Marc B's suggestion
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
xhr.node.innerHTML = xhr.responseText;
xhr.node.style.display = "block";
}
}
xhr.send(post);
}
now when i check this in firebug
i can see that the div
element is created and appended to the categories
element and its display is set to hidden
. also the ajax post
requests are being sent and the response is being received as expected. But the innerHTML
property of div
is not set and neither its display is set to block
.
This means that the function getLinks
loses the div
reference.
when i type console.log(div)
in the firefox console it says ReferenceError: div is not defined
.
can somebody explain whats going on here?
in response to Franks's comment i changed readystate
to readyState
and i am able to attach the response of the last ajax request to the dom. so that makes it obvious that the div
reference is being lost.