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.
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();
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.
Related
I have a JavaScript function that is attempting to closely emulate a form submit.
function fopen() {
var xhr = new XMLHttpRequest();
xhr.open("POST", open_url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
create: 0,
jobtype: jobtype,
name: document.getElementById("file-selector").value
}));
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
document.write(xhr.responseText);
}
else {
console.log('ErR0r')
}
}
}
The behavior is close to identical, but the URL is not being updated after the response. I see there is an xhr.responseURL attribute but how can I actually get this to show in the address bar? And is there an exact full JavaScript implementation of form submit I can refer to in order to keep things as similar as possible?
To change the page's URL, set window.location.href.
I am trying to figure out how to toggle the style display using plain javascript.
I have an XLMHttpRequest(). It works. The UI display is what I am working on. I would like the spin icon to show while the data is being loaded to the database. So, my code turns on the icon but the problem is when I add
document.getElementById('loading').style.display = "none";
to reset it to hidden. It never shows. So, here is my code.
function runScript()
{
let xhr = new XMLHttpRequest();
xhr.open('GET', 'wenoconnected.php', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onprogress = function() {
document.getElementById('loading').style.display = "block";
}
xhr.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
if (this.responseText === 'imported') {
alert('Update Complete');
}
document.getElementById('loading').style.display = "none";
}
}
xhr.send()
}
I tried to have the page just reload after the alert is shown but all that does is immediately reloads the page without executing the xhr.send(). That is why I would like to know what order is the code executed. That way I will know where to place the display = "none".
The latency is probably too low to notice the change (which can be verified by simulating high latency on the server). Try the following as an alternative:
From:
function runScript()
{
let xhr = new XMLHttpRequest();
xhr.open('GET', 'wenoconnected.php', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onprogress = function() {
document.getElementById('loading').style.display = "block";
}
xhr.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
if (this.responseText === 'imported') {
alert('Update Complete');
}
document.getElementById('loading').style.display = "none";
}
}
xhr.send()
}
To:
function runScript()
{
let xhr = new XMLHttpRequest();
xhr.open('GET', 'wenoconnected.php', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
if (this.responseText === 'imported') {
alert('Update Complete');
}
document.getElementById('loading').style.display = "none";
}
}
document.getElementById('loading').style.display = "block";
xhr.send()
}
Assumptions:
The GET request latency is slow enough that you'll see the indicator
There is no other issue, related to CSS/HTML, that would prevent the indicator from showing
Disregarding the obvious, like; whether the function is being executed, no typos for identifiers that’d prevent relevant code from executing, etc.
I am on http://localhost:8000/index.html
When I press a link, I want it to go to localhost:8006/someAddress and select element with id='157579' AND press button with id='1787' which will cause an iframe further down my html to show something different.
I have made some pseudo code that somewhat shows what I want, but I am having a hard time converting it into something functional:
<body>
<script>
function Scenario1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
GoTo http://localhost:8006/SomeAddress
document.getElementById("157579").Select
Button("1787").Press
}
}
</script>
</body>
Is this possible to do, or is there an alternative? I understand that I have to do something with AJAX or jQuery or something similar, right?
use jquery click event when in your onload is triggered like $('#157579').click();
let xhr = new XMLHttpRequest();
xhr.open('GET', '/article/xmlhttprequest/example/load');
xhr.send();
xhr.onload = function() {
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
$('#157579').click();
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`);
}
};
xhr.onerror = function() {
alert("Request failed");
};
On a webpage, once images have been downloaded and rendered, I need to determine an image's file size (kb) within the browser context (so I could display that info on the page, just below the image)
The easiest way is probably with a HEAD request returning the Content-Length:
function fileSize(img, func) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', img.src, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
func(xhr.getResponseHeader('Content-Length'))
}
}
xhr.send()
}
Usage
fileSize(imgNode, function(size) {
// ...
})
here is my html:
<html><body>
page starts here
this is a test page
top:
<script id="invoc_code" type="text/javascript">
window.onload = function() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
var body = document.body;
if (xhr.readyState == 4 && xhr.status == 200) {
if(body.firstChild){
body.insertBefore(xhr.response, body.firstChild);
} else {
body.appendChild(xhr.response);
}
}
};
xhr.open("GET", "http://google.com", true);
xhr.send();
};
</script>;
page ends here
</body></html>
line body.insertBefore(xhr.response, body.firstChild); results to "NotFoundError: An attempt was made to reference a Node in a context where it does not exist". Can you please tell me what is the reason?
Thanks in advance
The insertBefore method expects a DOM element as its first parameter. If the XHR response is a HTML string, then you need to create one using this. Depending on your required DOM output you could do something like this:
var newElem = document.createElement("div");
newElem.innerHTML = xhr.response;
body.insertBefore(newElem, body.firstChild);