404 JavaScript issue - javascript

I have a strange problem.
Sometimes error 404 appears. But not always and thats the strange part..
I made a page with javaScript and at the end of the page iam changing images with this java script function
var backGround = ['img/wall1.jpg', 'img/wall2.jpg', 'img/wall3.jpg'];
var header = document.getElementById('headerBlanco');
var i = 0;
setInterval(function(){
if(i !== backGround.length - 1){
i++;
}else{
i = 0;
}
header.style.backgroundImage = 'url(' + backGround[i] + ')';
}, 6000);
It works like i wanted but sometimes the browser cant find a image and error 404 appears..
Failed to load resource: the server responded with a status of 404 (Not Found)
can somebody explain me why this can happen?
This is the site where you can see it.
You need to click on the buttons to see it happen.
http://www.leerappel.nl

The error you have mentioned in your comment is caused by header being null. This means that document.getElementById('headerBlanco') yields null. That means that headerBlanco does not necessarily exist. Make sure that the element exists and your url is correct. Also, instead of
if(i !== backGround.length - 1){
i++;
}else{
i = 0;
}
you can do this:
i = (i + 1) % backGround.length;
EDIT:
It turns out I misunderstood the situation. I mistakenly believed that the first comment of the question was made by the author. Since the item has a value, the 404 can most probably be attributed to internet connection problems.

Related

Get XMLHttpRequest connection status as seen in browser console

I want to check, if a website is reachable with XMLHttpRequest.
I wrote a JS-function: UrlExsists(url); to try and establish a connection.
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
if (http.status != 404) {
console.log("did work:" + url)
} else {
console.log("did not work:" + url)
}
};
When i go to my browser console and call the function like so:UrlExsists("https://www.google.com/");, the following is displayed in the console:
"XHR HEAD https://www.google.com/ [HTTP/2.0 200 OK 668ms]"
But It fails due to "Cross-Origin Request Blocked" and a Network Error occurs. = >img as reference
If I call UrlExsists("https://www.google.com/test"); the following is displayed:
"XHR HEAD https://www.google.com/test [HTTP/2.0 404 Not Found 0ms]"
And again "Cross-Origin Request Blocked" and Network Error. = > img as reference
Now these Status codes 404 and 200 are exactly, what i want, but how do i get these in javascript, to determine if the given website is available?
And if I'm on the wrong track, can someone maybe nod me to the right one?
I think, I found a solution for my problem.
The fetch API seems to do just what I want.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I did as the accepted answer from Kaiido instructed:
Check if online resource is reachable with JavaScript, not requiring the The Same Origin Policy to allow it
It is not possible due to the CORS error (you have no right to load other site's script, if it is not enable with Cross-Origin Resource Sharing: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). You just cant get the information, not even the HTTP response code.
The only workaround I see is append to the DOM a css request. And checking if the css successfully loaded. But its not a general solution, you need to pick some css class and check if it is loaded. And also you need to disable the cache with HTML meta tags.
You also can append css link tag dynamically (description: https://gist.github.com/chrisyip/1403858)
<link rel="stylesheet" type="text/css" href='https://mysite/custom.css'>
In the cusom css you need some unique class like:
.url-exists {
}
And after some delay (like 3-5 seconds timeout), you check if the css is successfully loaded:
function verifyStyle(selector) {
var rules;
var haveRule = false;
if (typeof document.styleSheets != "undefined") { //is this supported
var cssSheets = document.styleSheets;
outerloop:
for (var i = 0; i < cssSheets.length; i++) {
//using IE or FireFox/Standards Compliant
rules = (typeof cssSheets[i].cssRules != "undefined") ? cssSheets[i].cssRules : cssSheets[i].rules;
for (var j = 0; j < rules.length; j++) {
if (rules[j].selectorText == selector) {
haveRule = true;
break outerloop;
}
}//innerloop
}//outer loop
}//endif
return haveRule;
}//eof
var ok = verifyStyle(".url-exists");
If the variable ok is true then the given url (https://mysite/) is accessible.

JSONP request not working showing error 404

I am trying to load some data from whois.com but the request is failing with 404 not found. In the past it was working but not sure why it stops now. it is a small java script function to find Domain Age.
URL - mygovjobs.in/tools Code snippet:
$(document).ready(function () {
var domainCheckerUrl = "http://www.whois.com/whois/google.com";
/*This line is giving error */ $.getJSON("http://alloworigin.com/get?url=" + encodeURIComponent(domainCheckerUrl) + "&callback=?", function(data){
$('#urlname')[0].value = "";
var dataElement = $(data.contents).find('#registryData')[0];
Namaste Mahesh,
from the site, it looks like the server is not fully functional yet, some configurations are missing! Maybe that's the reason you are getting 404.
have a look at the snapshot of alloworigin.com.

HTML Img's failing to load

Just for fun, i'm trying to implement a "15 puzzle", but with 16 images (from 1 music photo) instead.
The thing is split into 2 scripts / sides. 1 Python CGI script that will perform the Last.FM query + splitting the image in Y x Z chunks. When the python script finishes it outputs a JSON string that contains the location (on server), extension etc.
{"succes": true, "content": {"nrofpieces": 16, "size": {"width": 1096, "height": 961}, "directoryname": "Mako", "extension": "jpeg"}}
On the other side is a HTML, JS, (CSS) combo that will query the CGI script for the images.
$(document).ready(function () {
var artiest = $("#artiest")
var rijen = $("#rijen")
var kolommen = $("#kolommen")
var speelveld = $("#speelveld")
var search = $("#search")
$("#buttonClick").click(function () {
var artiestZ = artiest.val()
var rijenZ = rijen.val()
var kolommenZ = kolommen.val()
$.getJSON("http://localhost:8000/cgi-bin/cgiScript.py", "artiest=" + artiestZ + "&rijen=" + rijenZ + "&kolommen=" + kolommenZ, function (JsonSring) {
console.log("HIIIIII")
if (JsonSring.succes === true){
console.log(JsonSring)
var baseUrl = "http://localhost:8000/"
var extension = JsonSring.content.extension
var url = baseUrl + JsonSring.content.directoryname + "/"
var amountX = rijenZ
var amountY = kolommenZ
for (var i = 0; i < amountX; i += 1){
for (var p = 0; p < amountY; p += 1){
console.log("HI")
var doc = new Image
doc.setAttribute("src", url + JsonSring.content.directoryname + i + "_" + p + "." +extension)
document.getElementById("speelveld").appendChild(doc)
}
}
}else {
// Search failed. Deal with it.
}
})
})
})
where the various id's link to various HTML elements. (Text Fields & Buttons & Div's).
Beneath is a screenshot of the full folder that contains the image files.
Now, coming to the point. All the HTML img tags with src seem correct, yet. Some images don't load, yet other do. I also noticed that all images failed to load in 2s intervals. Is there some kind of timeout, or so?
All this is being ran from a local machine, so disk speed and cpu shouldn't really affect the matter. Also, from what I understand: The call for making the img tags etc is done in a callback from the getJson, meaning it'll only run when getJson has finished / had a reply.
Does the great StackOverFlow community have an idea what's happening here?
To share my knowledge/experiences with the great StackOverflow community,
Small backstory
After progressing a bit further into the project I started to run into various issues going from JSON parsing to not having Allow-Control-Allow-Origin: * headers, making it very hard to get the Ajax Request (Client ==> Python CGI) done.
In the meantime I also started dev'ing on my main desktop (which for some reason either has massive issues with Python versioning or has none). But due to the terminal on my desktop having Python 3.4+ , there was no module CGIHTTPServer. After a small amount of digging, I found that CGIHTTPServer had been transfered into http.server, yet when running plain old python -m http.server, I noticed the CGI script wouldn't run. It would just display. Ofcourse, I forgot the option -cgi.
Main solution
The times I was succesfully using CGIHTTPServer, I had troubles. The images wouldn't load as described above. I suspect that the module just couldn't take the decent amount of requests. Meaning that when suddenly Y x Z requests came in, it would struggle to deliver all the data. ==> Connection Refused.
Since switching to python -m http.server -cgi, no problems what so ever. Currently working on a Bootstrap Grid for all those images!
Thx #Lashane and #Ruud.

Why would and img onerror handler execute if image works fine

I have implemented the onerror attribute for some images in order to detect the ones that are missing in my site.
This is the code:
<script>
function imageError(element) {
var noPicUrl = "${noPicUrl}";
var imageFailUrl = "/site/image/fail?mediaUrl=" + encodeURIComponent(element.src) + "&redirectUrl=" + encodeURIComponent(noPicUrl);
element.onerror = "";
element.src = imageFailUrl;
}
</script>
<img src="${poiPic}" onerror="imageError(this);"/>
As you can see, when an image fails, then the following url is called:
/site/image/fail?mediaUrl=" + encodeURIComponent(element.src) + "&redirectUrl=" + encodeURIComponent(noPicUrl)
This is a service that saves the mediaUrl that failed so that then I can check those and returns a redirect to the redirectUrl. That is working just fine. I just tested it and it logs perfectly.
But the problem was when I uploaded this to production and the logs started.. There where like 200 images in the log. But only 4 of them were really deleted and the link didn't work. The other ones just worked perfectly..
What could be causing this?
Image loading errors are difficult to manage because sometime error occoured fr cache problem, something for connection, other time is due to 404 error. Different browser manage these errors in a lot of way
IMHO the best way to manage image loading errors is to use the ImagesLoaded plugin of jquery
http://imagesloaded.desandro.com/

Why does dojo.xhrGet needs different kinds of url to work on different computers (pc/mac)?

i'm writing an greasemonkey script for somebody else. he is a moderator and i am not. and the script will help him do some moderating things.
now the script works for me. as far as it can work for me.(as i am not a mod)
but even those things that work for me are not working for him..
i checked his version of greasemonkey plugin and firefox and he is up to date.
only thing that's really different is that i'm on a mac and he is pc, but i wouldn't think that would be any problem.
this is one of the functions that is not working for him. he does gets the first and third GM_log message. but not the second one ("got some(1) ..").
kmmh.trackNames = function(){
GM_log("starting to get names from the first "+kmmh.topAmount+" page(s) from leaderboard.");
kmmh.leaderboardlist = [];
for (var p=1; p<=(kmmh.topAmount); p++){
var page = "http://www.somegamesite.com/leaderboard?page="+ p;
var boardHTML = "";
dojo.xhrGet({
url: page,
sync: true,
load: function(response){
boardHTML = response;
GM_log("got some (1) => "+boardHTML.length);
},
handleAs: "text"
});
GM_log("got some (2) => "+boardHTML.length);
//create dummy div and place leaderboard html in there
var dummy = dojo.create('div', { innerHTML: boardHTML });
//search through it
var searchN = dojo.query('.notcurrent', dummy).forEach(function(node,index){
if(index >= 10){
kmmh.leaderboardlist.push(node.textContent); // add names to array
}
});
}
GM_log("all names from "+ kmmh.topAmount +" page(s) of leaderboard ==> "+ kmmh.leaderboardlist);
does anyone have any idea what could be causing this ??
EDIT: i know i had to write according to what he would see on his mod screen. so i asked him to copy paste source of pages and so on. and besides that, this part of the script is not depending on being a mod or not.
i got everything else working for him. just this function still doesn't on neither of his pc's.
EDIT2 (changed question): OK. so after some more trial and error, i got it to work, but it's still weird.
when i removed the www-part of the url thats being use in the dojo.xhrGet() i got the finally the same error he got. so i had him add www to his and now it works.
the odd thing is he now uses a script with the url containing "www" and i'm using a script with an url without "www"...
so for me:
var page = "http://somegamesite.com/leaderboard?page="+ p;
and for him:
var page = "http://www.somegamesite.com/leaderboard?page="+ p;
Why don't you have him try logging into an account that is not a moderator account so that you eliminate one of your variables from your problem space.
It's possible that the DOM of the page is different for a moderator than for a regular user. If you're making assumptions about the page as a regular user that are not true as a moderator, that could cause problems.
I suspect that to fix it, you may need access to a moderator account so you can more easily replicate the behavior.
ooops. it seemed that the url of this gamesite is accessible as www.gamesite.com as well as gamesite.com (without the www.part). this caused the problem.
sorry to bother you'all.
i go hide in shame now...

Categories