What is different about xmlhttprequest in Firefox - javascript

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();

Related

Replace Element After 3 Clicks With Cookie Logging Script [HELP]

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.

Parallel asyncronous XMLHttpRequests are only calling back once

I am issuing two API calls in parallel, asynchronously so I don't lock up the browser , and I am only receiving one callback.
Here is the code
/* Loop runs twice, from 0 to 1 */
for(var AccountIndex in walletForm.masterpublicKey){
/* Bunch of code, then... */
/* Construct an API call to Insight */
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://insight.bitpay.com/api/addrs/" + stringOfAddresses + "/txs?from=0&to=100", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
$scope.$apply(function () {
txListInsight.txs[AccountIndex] = ( JSON.parse(xhr.responseText));
/* Set semaphore */
txListInsight.txsReady[AccountIndex] = true;
parseTransactions(AccountIndex);
console.log(txList);
})
}
}
xhr.send();
}
I can even see the two requests in the Chrome Dev Console Network Tab and the responses are correct. Why am I only getting one callback and not two? Is my second callback overwriting the reference to the first one?
Why is there a library on the Internet called “AsyncXMLHttpRequest”? I am using AngularJS as well--shall I look into "promises"?
Another option would be to avoid the problem entirely by combining my two API requests into one, but I'm not sure what the character limit is.
I think explicitly invoking function with the current AccountIndex should work, notice the closure
var xhrs = {};
for(var AccountIndex in walletForm.masterpublicKey){
(function(AccountIndex) {
xhrs[AccountIndex] = new XMLHttpRequest();
xhrs[AccountIndex].open("GET", "https://insight.bitpay.com/api/addrs/" + stringOfAddresses + "/txs?from=0&to=100", true);
xhrs[AccountIndex].onreadystatechange = function() {
if (xhrs[AccountIndex].readyState == 4) {
$scope.$apply(function () {
txListInsight.txs[AccountIndex] = ( JSON.parse(xhrs[AccountIndex].responseText));
/* Set semaphore */
txListInsight.txsReady[AccountIndex] = true;
parseTransactions(AccountIndex);
console.log(txList);
})
}
}
xhrs[AccountIndex].send();
})(AccountIndex);
}

XMLHttpRequest that is being Aborted

I'm looking over a bit of code that deals with XHR. It looks like the first XHR.send() is being done successfully and then the subsequent one is Aborted before it gets to it's .send()
Quick in dirty:
url = "http://192.168.1.1/cgi-bin/test.cgi";
data = "1235,123,21,1232,12321,432";
myXHR = new Array();
for(var i = 0; i < 2; i++) {
myXHR[i] = new XMLHttpRequest();
myXHR[i].open("POST", url, true);
myXHR[i].onerror = function() {
alert("Error occurred");
};
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
// do some setting up of XHR headers
myXHR[i].send(data);
myXHR[i] = null;
}
What could be happening that would cause Firebug to show Abort before the second .send() is done?
Try this:
url = "http://192.168.1.1/cgi-bin/test.cgi";
data = "1235,123,21,1232,12321,432";
var myXHR = [];
for(var i = 0; i < 2; i++) {
myXHR[i] = new XMLHttpRequest();
myXHR[i].open("POST", url, true);
myXHR[i].onerror = function() {
alert("Error occurred");
};
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
// do some setting up of XHR headers
myXHR[i].send(data);
myXHR[i] = null;
}
When I run this code I get TypeError: myXHR[i] is undefined (on the stock firefox 20 install on my mac... what version are you on)?
At any rate, I can see one issue with this (i.e. myXHR[i] will be undefined...) that might also apply to you, in particular with:
myXHR[i].onload = function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
};
Because this is triggered asynchronously i will have been incremented to 2, which is of course going to be outside the bounds of the two element myXHR array. Have you tried closing over the value of i, like so:
myXHR[i].onload = (function(i) {
return function() {
if(myXHR[i].status == 200) {
alert("Yay I worked");
var data = myXHR[i].responseText;
}
}
})(i);
Because once I correctly save that i value in that function body this code will succeed for both calls.
I know this isn't the exact issue you're having, but I think it will be an issue regardless so you may as well give it a go right? It's not as though there have been a huge number of other answers unfortunately.
hope this helps..
Found out what was happening.
The XHR was being aborted because there was no return value from the webserver that the request was being sent to. The web server is a custom based one that we seem to be using the someone changed the code so that it wasn't sending a 200 Success OK even if the data sent to it had no data coming back.
All good now. Thanks for the help.

Javascript Auto-fresh XMLHttpRequest problem

I'm writing a desktop gadget which should refresh every 10 minutes or so (It's ten seconds here). What I've determined is that every time I execute the setTimeout, the XML doesn't load again.
I don't know what kind of problem this is. I made sure that the objects are set to null, but they don't re-initialize and I'm left with a blank XML object.
setTimeout("bg_load();getXML()",10000);
function getXML()
{
stat = readSetting();
url = "http://www.weather.gov/xml/current_obs/" + stat[0] + ".xml"
rssObj = new XMLHttpRequest();
rssObj.open("GET", url, false);
rssObj.onreadystatechange = function() {
if (rssObj.readyState === 4) {
if (rssObj.status === 200) {
document.getElementById("gadgetContent").innerHTML = "";
rssXML = rssObj.responseXML;
} else {
var chkConn;
document.getElementById("gadgetContent").innerHTML = "Unable to connect...";
}
} else {
document.getElementById("gadgetContent").innerHTML = "Connecting...";
}
}
rssObj.send(null);
getImage(rssXML);
getText(rssXML);
rssObj = null; rssXML = null;
}
With SJAX (Synchronous Ajax), you shouldn't use 'onreadystatechange', and in the code, you pull the response text directly out of the XMLHttpRequest after sending.
Don't Use onreadystatechange:
https://developer.mozilla.org/en/xmlhttprequest#onreadystatechange
Example of pulling the responseText out: http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX

Strange javascript behavior - multiple active XMLHttpRequests at once? Long running scripts?

I'm attempting to issue two concurrent AJAX requests.
The first call (/ajax_test1.php) takes a very long time to execute (5 seconds or so).
The second call (/ajax_test2.php) takes a very short time to execute.
The behavior I'm seeing is that I /ajax_test2.php returns and the handler gets called (updateTwo()) with the contents from /ajax_test2.php.
Then, 5 seconds later, /ajax_test1.php returns and the handler gets called (updateOne()) with the contents from /ajax_test2.php still!!!
Why is this happening?
Code is here: http://208.81.124.11/~consolibyte/tmp/ajax.html
This line:-
req = new XMLHttpRequest();
should be:-
var req = new XMLHttpRequest();
As AnthonyWJones stated, your javascript is declaring the second AJAX object which first overwrites the req variable (which is assumed global since there is no var) and you are also overwriting the ajax variable.
You should separate your code i.e:
function doOnChange()
{
var ajax1 = new AJAX('ajax_test1.php', 'one', updateOne);
var ajax2 = new AJAX('ajax_test2.php', 'two', updateTwo);
}
function AJAX(url, action, handler)
{
if (typeof XMLHttpRequest == "undefined")
{
XMLHttpRequest = function()
{
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
throw new Error( "This browser does not support XMLHttpRequest." )
};
}
url = url + '?action=' + action + '&rand=' + Math.random()
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4)
{
if (req.status == 200)
{
alert('' + handler.name + '("' + req.responseText + '") ')
handler(req.responseText)
}
}
}
req.open("GET", url, true);
req.send(null);
}
Regards
Gavin
Diodeus and Mike Robinson:
You guys didn't read my post fully. I know that one of the pages takes longer to execute than the other. That is the expected behavior of each page.
HOWEVER if you read my original post, the problem is that the callback for both pages ends up getting called with the HTML contents of the first page only.
AnthonyWJones and Gavin:
Thanks guys! That works like a charm! I guess I need to brush up on my Javascript!

Categories

Resources