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");
};
Related
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.
It is my AJAX call with setTimeout
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById('mainContent').style.display = 'none';
if (this.readyState == 4 && this.status == 200) {
xhttp.onload = function(){
document.getElementById("mainContent").innerHTML = this.responseText;
setTimeout(function(
document.getElementById("mainContent").style.display = 'block';
),1000);
}
}
};
xhttp.open("POST", "system.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lang="+lang);
I want detect when ajax is fully loaded and I have also solution here
I have solution here but I can't understand how it work.
var oldOpen = XMLHttpRequest.prototype.open;
function onStateChange(event) {
// fires on every readystatechange ever
// use `this` to determine which XHR object fired the change event
}
XMLHttpRequest.prototype.open = function() {
// when an XHR object is opened, add a listener for its readystatechange events
this.addEventListener("readystatechange", onStateChange)
// run the real `open`
oldOpen.apply(this, arguments);
}
Can you example me how it work or write full code how it work ?
I got this code, to simple to have any errors and still...
I have a nav, where the onclick calls for clicker(nodenr) what should load an external site in an div.
function clicker(nodenr) {
var url=links[nodenr];
console.log(nodenr);
var request = new XMLHttpRequest();
request.open('GET', ''+url+'', true);
//request.open('GET', ''url, true);
request.onreadystatechange = function (event) {
if(request.readyState == 4) {
if(request.status == 200) {
console.log("hello");
document.getElementById("content").innerHTML = request.responseText;
}
else {
document.getElementById("content").innerHTML = "Service not loading.";
}
}
};
}
What basic error have I made? Please correct me. :)
I am sure there is something that I am missing from this code, I just can not figure out what it is.
Here is the main page:
<script>
function wwCallback(e) {
document.write(e.data);
}
function wwError(e) {
alert(e.data)
}
$(document).ready(function () {
var worker = new Worker("sync.js");
worker.onmessage = wwCallback;
worker.onerror = wwError;
worker.postMessage({
'cmd': 'downloadUser',
'url': 'server.php'
});
console.log("WW Started");
});
</script>
Server.php simply echoes a JSON string and I have verified that it is both valid and working using normal ajax requests.
Here is my web workers code:
function getData(url) {
var req = new XMLHttpRequest();
//expect json
req.open('GET', url);
req.send(null);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
self.postMessage(req.responseText);
}
}
}
}
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'downloadUser':
getData(data.url);
}
self.close();
}, false);
Could anyone point me in the right direction?
Your problem is in your WebWorker XHR call. You've opened the request, then immediately sent it before you've set up the event handler to handle the response. You just need to move the req.send(null); call below the code that sets up the event handler.
Try this:
function getData(url) {
var req = new XMLHttpRequest();
//expect json
req.open('GET', url);
// req.send(null); // remove this line from here.
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
self.postMessage(req.responseText);
}
}
}
req.send(null); // make the request after your readystatechange
// handler is set up.
}
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'downloadUser':
getData(data.url);
}
self.close();
}, false);
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);