Reputation: 513
For the last hour or so, I've been trying to solve a problem, which came up when I tried to change html of an element from XMLHttpRequest.
xhr.open('GET', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(document.getElementById('notifications-navbar').innerHTML);
document.getElementById('notifications-navbar').innerHTML = xhr.responseText;
console.log(xhr.responseText);
console.log(document.getElementById('notifications-navbar').innerHTML);
} else {
console.log('error');
}
};
xhr.send();
The output of the console logs were: pastebin
So in the console.log we can see the change to the innerHTML was made, however there is no change whatsoever when I have a look on the elements via Chrome inspect and also there is no change in the browser. I even tried to remove every other JS scripts that were being loaded and just make a simple change of the innerHTML outside of XHLHttpRequest, but that didn't help too. Please if you could help I would be really happy.
Upvotes: 0
Views: 559
Reputation: 513
Okay, sorry guys, I found my mistake, I had in my HTML two elements with ID notifications-navbar and only the first one was being changed. Thanks for your help anyway.
Upvotes: 0
Reputation: 4993
Not sure what your EndPoint URL is , but I wrote this for you and it works just fine. Hope this can help you!
HTML
<div id = "notifications-navbar"></div>
Javascript
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "http://jsonplaceholder.typicode.com/posts";
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(document.getElementById('notifications-navbar').innerHTML);
document.getElementById('notifications-navbar').innerHTML = xhr.responseText;
console.log(xhr.responseText);
console.log(document.getElementById('notifications-navbar').innerHTML);
} else {
console.log('error');
}
};
xhr.send();
Upvotes: 1