I have this JavaScript worker for fetching data on the PHP backend.
ajax-worker.js
self.onmessage = function(e){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
postMessage(xhttp.responseText);
}
};
xhttp.open("GET", e.data, true);
xhttp.send();
}
and initiate a worker by
let worker = new window.Worker('http://localhost:8100/ajax-worker.js');
worker.postMessage('http://localhost:8100/Audit/get_total_confirmed');
worker.onmessage = function(e){
var e = JSON.parse(e.data);
document.querySelector('#stat_confirmed_listings').innerHTML = e.msg;
}
Everything is working except if I browse other pages in my website, it takes very long time to load and sometimes it returns "unreachable page" error and not until the worker completes the request or restart the server, the page then will load. What might be wrong?
Below is the view of my console console -> sources:
Related
I'm consuming a JSON API with JavaScript and adding that content in HTML with append but when you go to another page and click Back in the browser the content is reloaded so I want to know a way to avoid this, this is the JavaScript code I'm Using.
var request = new XMLHttpRequest();
request.open('GET', 'https://localhost:3000/api', true);
request.onload = function () {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(v => {
const card = '<span><div class="card">v.content</div></span>';
$("#data").append(card);
});
}else{
console.log('Error al cargar el contenido');
}
}
request.send();
thanks for your help
You would have to save the response from the get request locally and load from that.
Checkout this answer to a similar question https://stackoverflow.com/a/17104536/10997917
I am new on Html. What i need is this.
I have an index.html file on a server which is blank.
I open it and write some text inside the body all the time.
What i want is that when i save the html,
the new data to appear on my clients browser
without the need to refresh or reload the page.
I have no idea on how to do it,so i haven't try anything.
Is it possible? Is it simple?
This is a sample javascript code to read an online url and update the content container with the result.
I couldn't find a simple live update page so used my own website readme in github...
var timeout = 2000,
index = 1,
cancel = false,
url = 'https://raw.githubusercontent.com/petjofi/krivoshiev.com/master/README.md';
function update() {
updateIndex();
load(url, done);
if (!cancel) setTimeout(update, timeout);
}
function updateIndex() {
document.getElementById("index").innerHTML = index++;
}
function done(result) {
document.getElementById("content").innerHTML = result;
}
function load(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
}
<button onclick="update()">start</button>
<button onclick="cancel=true">stop</button>
<span>updating: <span id="index">0</span></span>
<div style="margin-top: 20px" id="content"></div>
I have a short snippet of Javascript which I want to poll a server every couple of seconds and update the DOM.
function updateCard() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
window.setInterval(updateCard,2000);
On most browsers that's what happens. There are a few one-off calls to updateCard, but on the whole the server shows ~1/2 connection per second per client.
However, when I access the page in Firefox on Android (49.0) the browser starts continuously polling /curr_card/, tens of times a second.
I've seen people suggest replacing the setInterval line with window.setInterval(function() {updateCard();},2000);, this doesn't help.
I'm pretty new to Javascript and AJAX, so have no idea why this is happening. Is it a bug in FF? I can post more code if requested.
Thanks in advance.
After testing and discussing in OP's comments, we concluded this must be an issue specific to Firefox on the OP's HTC M7, as it could not be reproduced on the same version Firefox on a Galaxy S7.
That may happen not only with Firefox on some device.
It may happen when response has not finished because of servers late answer but it sends another request and so on...
What if to do like this:
function updateCard(before, after) {
if(before) {
before();
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
if(after) {
after();
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
var updateCardRunning = false;
setInterval(function() {
if(updateCardRunning === true) {
console.log('postponing to next schedule');
return;
}
updateCard(
function() {updateCardRunning = true;},
function() {updateCardRunning = false;}
);
}, 2000);
or:
function updateCard() {
var xhttp = new XMLHttpRequest();
window.xhttp = xhttp;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
card = JSON.parse(this.responseText);
document.getElementById("season").innerHTML = card.season;
}
};
xhttp.open("GET", "/curr_card/", true);
xhttp.send();
}
window.onload = updateCard;
setInterval(function() {
if(window.xhttp) {
window.xhttp.abort();
}
updateCard();
}, 2000);
Hey guys, this is driving me absolutely insane so I wanted to ask the experts on this site to see if you know how to do it =)
I'm trying to create some javascript code that can read out elements of a web page (eg. what does the first paragraph say?). Here's what I have so far, but it doesnt work and I cant figure out why:
<script type="text/javascript">
<!--
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
alert("done loading");
var responseDoc = new DOMParser().parseFromString(req.responseText, "text/xml");
alert(responseDoc.evaluate("//title",responseDoc,null,
XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}
else {
document.write("<error>could not load page</error>");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.apple.com", true);
req.send(null);
// -->
The alert that keeps appearing is "null" and I can't figure out why. Any ideas?
This may be due to cross domain restriction... unless you're hosting your web page on apple.com. :) You could also use jQuery and avoid writing all that out and/or dealing with any common possible cross-browser XML loading/parsing issues. http://api.jquery.com/category/ajax/
Update:
Looks like it may have something to do with the source web site's Content-Type or something similar... For example, this code seems to work... (Notice the domain loaded...)
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
//alert("done loading");
//alert(req.responseText);
var responseDoc = new DOMParser();
var xmlText = responseDoc.parseFromString(req.responseText, "text/xml");
try{
alert(xmlText.evaluate("//title",xmlText,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}catch(e){
alert("error");
}
}
else {
document.write("could not load page");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.jquery.com", true);
req.send(null);
I also tried loading espn.com and google.com, and noticed they both have "Content-Encoding:gzip" so maybe that's the issue, just guessing though.
I'm experiencing an issue with XMLHttpRequest. If there is no Internet connection, my request is not timing out and thus freezing the browser. Here is the request code:
var jsonData = new XMLHttpRequest();
jsonData.open('GET', urltest, false);
jsonData.Timeout = 100;
jsonData.send(null);
if(jsonData.status == 200) {
alert(jsonData.statusText);
}else{
alert(jsonData.statusText);
}
How do I abort the request if the server doesn't respond?
I made some changes to your code, and I left some comments where I made changes explaining what's going on. I hope it helps!
var jsonData = new XMLHttpRequest();
jsonData.open('GET', urltest);/* I removed the false, because it kept the browser
waiting for the page to load to continue, and it didn't let it do other things
while it was still loading.*/
jsonData.Timeout = 100;
jsonData.send();
jsonData.onreadystatechange = function() {/*Each time readyState changes value,
run this code.*/
if (jsonData.readyState == 4) {/*When readyState is equal to 4,
the page has fully loaded.
Only run the code when it's 4,
not when it's still loading.*/
if (jsonData.status == 200) {
alert(jsonData.statusText);
} else {
alert(jsonData.statusText);
}
// More things to do when the page has fully loaded...
}
}