Been trying to replace an element after 3 clicks on it with cookie logging. So the webserver remembers when 3 clicks have exceeded on a specific element and replaces it with url one. So it should of been simple but, I tried finishing mine and this is what, I came up with:
document.getElementById("replace1").innerHTML = localStorage.getItem("replace1");
let count = 0;
function loadDoc() {
var xhttp = new XMLHttpRequest();
let callback = function() {
count++;
if (!(count >= 3 && this.readyState == 4 && this.status == 200)) {
localStorage.setItem("replace1",this.responseText);
}
iframe1.click(callback);
xhttp.open("GET", "https://natevanghacks.com/replacements/yoinkexecutor2.html", true);
xhttp.send();
}
};
As predicted it won't work for some reason. All, I am trying to do is replace element after 3 clicks on it with the url one and webserver remembers the change so it doesn't return back to its default state. Whether with database or in Cookie, sessionStorage, localStorage.
Related
I'm using an XMLHTTPRequest to receive data from a PHP file. The PHP file will echo at a number, say 6, and the XMLHTTPRequest will grab it. This is an attempt to make the graph live.
The problem I'm having relates to ChartJS and these requests.
var Data;
function loadXMLDOC() {
var request = new XMLHttpRequest(); // create http request
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
Data = this.responseText;
myChart.data.labels.push(" ");
myChart.data.datasets[0].data.push(Data);
// re-render the chart
myChart.update();
}
}
request.open('GET', "data.php", true);
request.send(); // send the request
}
setInterval(function(){
loadXMLDOC();
}, 1000)
window.onload = loadXMLDoc;
As I'm grabbing these numbers from a database, I only need the number once. However, it will repeat the number multiple times, not once.
Numbers Repeating on ChartJS
I was wondering how I would only get the number once and have it not repeat multiple times till the next number comes in?
As Manuel suggested you can check if the latest number added is the same number as you want to add. If this is the case dont add it. Side effect from this is, if the next number is actually the same number as the last one it also wont be added. To achieve this you can change your function to this:
if (request.readyState == 4 && request.status == 200) {
Data = this.responseText;
const chartData = myChart.data.datasets[0].data;
if (chartData[chartData.length - 1] === Data) {
return;
}
myChart.data.labels.push(" ");
myChart.data.datasets[0].data.push(Data);
// re-render the chart
myChart.update();
}
Another option is to let PhP not send the number if it already has been sent.
I have a problem with my for loop in ajax. I'm using this script to GET a list of images through an API:
let request = new new XMLHttpRequest();
request.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200) {
let img = JSON.parse(this.responseText);
for(let i = 0; i < img.totalHits; i++) {
$('#media').append(' <img src=" '+ img.hits[i].previewURL +' "> ');
}
}
};
request.open('GET', 'https://pixabay.com/api/key=************&per_page=100&image_type=' + image_type + '', true);
request.send();
When I go to Firefox Developer Edition console I have this problem:
When I go to google console I have this error:
I tried to fix without any result. Do you think it's a normal error when I use ajax?
Use img.hits.length instead of img.totalHits. totalHits is the total number of hits available, not the number returned by this call, which is limited by the per_page=100 parameter.
In your code, when i >= 100, you're trying to access outside the img.hits array, so img.hits[i] is undefined and you get an error trying to access its property.
You can call the API repeatedly with increasing values of the page parameter to get successive pages of results, until you get all totalHits results.
I'm trying to write some java script code that will (if the file exists) add its content to the web page, if it doesn't exist then it will check if the next file exists. I currently have it displaying the data if the file exists, however throws
GET http://localhost:8080/temp1.xml 404 (Not Found)
xmlhttp.onreadystatechange # friends.html:56
XMLHttpRequest.send (async)
(anonymous) # friends.html:95
if the file doesn't exist.
I've already tried adding i try catch around different parts but none of them seem to stop the error from occurring. ive also been trying to find a decent guide on how to handle not found errors but cant seem to find one that would work in my case.
this is the code I have without the try excepts.
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
JSObj = JSON.parse(this.responseText);
console.log(JSObj.friends.length);
for (i = 0; i < JSObj.friends.length; i++) {
name = JSObj.friends[i].name;
xhttp1.open("GET", "temp"+ i +".xml", true);
xhttp1.send();
};
};
};
this is the code I have with the try excepts
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
JSObj = JSON.parse(this.responseText);
console.log(JSObj.friends.length);
for (i = 0; i < JSObj.friends.length; i++) {
name = JSObj.friends[i].name;
try{
xhttp1.open("GET", "temp"+ i +".xml", true);
xhttp1.send();
}catch(err){
console.log(err);
};
};
};
};
the output I'm getting is a blank page due to the error stopping the code I have working from working which is when the error above is output. I expect that it would just skip that file and go onto the next one.
That's not the way XMLHttpRequest works. Perceive the difference you're treating the call that run that code and what you're expecting open() method to do.
First you have asynchronously made a call to a URL you have not mentioned. When this process returned it called the onreadystatechange event which runned the code you posted in the question.
Then you expect open() method to function differently and use a try/catch. See the difference ?
See that you have setted the async parameter to true. So you are opening a whole new call on another object called xmlhttp1. With this 2nd call you create another XMLHttpRequest request that should be addressed by another onreadystatechange method to process it.
You can read more on using XMLHttpRequest here:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
More or less like this :
NOT TESTED PSEUDO-CODE
xmlhttp1 = new XMLHttpRequest();
xmlhttp1.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// whatever you want to do with the call to
// xhttp1.open("GET", "temp"+ i +".xml", true);
}
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
JSObj = JSON.parse(this.responseText);
console.log(JSObj.friends.length);
for (i = 0; i < JSObj.friends.length; i++) {
name = JSObj.friends[i].name;
xhttp1.open("GET", "temp"+ i +".xml", true);
xhttp1.send();
};
};
};
Please adapt this code. It's just to illustrate what I mean and probably will not work this way.
My code works in Chrome and Safari, but it hangs in FF.
I removed the parts of the code that aren't necessary.
I used console commands to show how far the first loop gets, and it will do the second log fine right before the xhr open and send commands.
If the open/send commands are present the loop only happens once, if I remove the open/send commands the loop completes successfully.
Currently using FF 62nightly, but this issue has plagued me since Quantum has come out and I'm now trying to figure out why it doesn't work right.
for (i = 0; i < length; i++) {
(function(i) {
// new XMLHttpRequest
xhr[i] = new XMLHttpRequest();
// gets machine url from href tag
url = rows[i].getElementsByTagName("td")[0].getElementsByTagName('a')[0].getAttribute('href');
// Insert the desired values at the end of each row;
// will try to make this customizable later as well
insertVNC[i] = rows[i].insertCell(-1);
insertSerial[i] = rows[i].insertCell(-1);
insertVersion[i] = rows[i].insertCell(-1);
insertFreeDiskSpace[i] = rows[i].insertCell(-1);
// the fun part: this function takes each url, loads it in the background,
// retrieves the values needed, and then discards the page once the function is complete;
// In theory you could add whatever you want without taking significantly longer
// as long as it's on this page
console.log(i);
xhr[i].onreadystatechange = function() {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
}
};
//"Get" the "Url"... true means asyncrhonous
console.log(url);
xhr[i].open("GET", url, true);
xhr[i].send(null);
})(i); //end for loop
}
I cannot tell you why it gives issues in Firefox. I would not trust sending off arbitrarily many requests from any browser
I would personally try this instead since it will not fire off the next one until one is finished
const urls = [...document.querySelectorAll("tr>td:nth-child(0) a")].map(x => x.href);
let cnt=0;
function getUrl() {
console.log(urls[cnt]);
xhr[i].open("GET", urls[cnt], true);
xhr[i].send(null);
}
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
if (cnt>urls.length) getUrl();
cnt++;
}
}
getUrl();
I am reading a comma separated text file from the server, i get the valuse but when i chage the comma seprated variables in the file, it doesn't load the correct result int the browser
while browser persist the first time variable list only, whlile it works correct in IE, in firefox i am facig this proble.
How to sort it out
var arrUserTags = new Array();
var txt;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/TinyEditor/TextFile.txt", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
txt = xmlhttp.responseText;
arrUserTags = txt.split(",");
alert(arrUserTags.length);
parse();
}
}
// Add some values to the list box
function parse() {
for (i = 0; i < arrUserTags.length; i++) {
mlb.add(arrUserTags[i], arrUserTags[i]);
alert('hi');
}
}
You server is presumably sending caching instructions that tell browsers the URI for the text file won't change for a while.
Either configure the server to send no cache headers, or change the URI (e.g. by adding a rand() query string to it).