Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialdevin leyba
7,209 PointsJust a quick question on why this doesnt work.
This doesnt work:
var button = document.getElementById("load");
function sendAJAX() {
xhr.send();
button.style.display ="none";
}
But this does:
function sendAJAX() {
xhr.send();
document.getElementById("load").style.display ="none";
}
Basically I just need a refresher from anyone kind enough to let me know why I cant store this element in a variable in this instance., I swear I have done this before but I know I am missing some small rule. Thanks for the help.
5 Answers
Steven Parker
231,269 PointsNeither one of these should work when "xhr" is not defined (it's not in the code shown). But both should work when it is assigned to an object with a working "send" method.
To confirm that the variable is not the issue, try both of these with the "xhr.send();
" line removed or commented.
devin leyba
7,209 Pointsxhr is defined near the top of my page. I just didn't post that part, but only the one that doesn't use the button variable works.
devin leyba
7,209 Pointsvar xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4){
document.getElementById("ajax").innerHTML = xhr.responseText ;
}
}
xhr.open("GET", "sidebar.html");
function sendAJAX() {
xhr.send();
document.getElementById("load").style.display ="none";
}
Steven Parker
231,269 PointsThis code only defines "sendAJAX", it doesn't call it. But the best way to confirm for yourself that the variable isn't the issue is to try the DOM code both ways without any of the AJAX stuff.
And to facilitate analysis and share the complete code (without formatting issues), make a snapshot of your workspace and post the link to it here.
Dusan Zivanovic
1,274 PointsWorks here. xhr.open('GET', 'sidebar.html');
var button = document.getElementById('load');
function sendAjax() {
xhr.send();
button.style.display = "none";
}
Luis Giraldo
Full Stack JavaScript Techdegree Graduate 27,531 PointsI was having the same issue, but it was because I had the script tags inside the head tag, when the JavaScript code loaded, the button element wasn't created yet, so the variable couldn't retrieve the element. To be able to fix that I just placed the script tags before the closing body tag. Here is an snapshot of my code, I hope this helps to answer your question!. https://w.trhou.se/bnbmk4bxxq