I'm using the following script to refresh my <iframe> every 60 seconds.
<script type=text/javascript>
setInterval(function() {
document.getElementById("tracker").src += "";
}, 60000);
</script>
I would like to show a different page/<iframe> if the refresh fails. For example, if I'm not connected to any network, then obviously any page refresh will show the "page not found" error.
Instead, I would like to display a different <iframe> (e.g. tracker2) or different page/message/image to say "Offline". Of course the <iframe> will keep refreshing itself until there's internet connection.
I'm pretty sure that's not possible, however I may be wrong. Is it possible?
If the <iframe> you're loading is on a different domain, then no, it's not possible. Otherwise, you can use Ajax to check the status:
var rq = new XMLHttpRequest();
rq.open('GET', document.getElementById('tracker').src, true);
rq.onreadystatechange = function() {
if(rq.readyState === 4) {
if(rq.status === 200) {
// All is well
} else {
// Show your backup element
}
}
};
rq.send(null);
You can check http code of your iframe and depending on that you can render another page
You can use Jquery ajax to load page content and check page status. For example:
<script type=text/javascript>
setInterval(loadIframe, 60000);
function loadIframe()
{
$.ajax({
type: 'GET',
url: 'document.getElementById('tracker').src',
success: function(data){
alert('horray! 200 status code!');
document.getElementById("tracker").src += "";
},
error: function(data){
//get the status code
if (code == 400) {
alert('400 status code! user error');
}
if (code == 500) {
alert('500 status code! server error');
}
},
});
}
</script>
Related
I have created a web page that displays data retrieved from a database via a jQuery $.ajax call. The web page is part of a digital signage system that will be displayed continuously.
The $.ajax response is formatted HTML generated server side. This HTML is then inserted into a div element after removing any existing HTML from the div.
I then attach a jQuery marquee plugin (http://aamirafridi.com/jquery/jquery-marquee-plugin) to some of the newly created div elements with the .marquee class.
var marqueeCounter = 0;
var appBusy = false;
function update() {
if (appBusy == false) {
$.ajax({
url: '/get/html/from/server',
cache: false,
success: function (response) {
$('#div-container').empty();
$('#div-container').html('');
$('#div-container').html(response);
$('.marquee').each(function () {
$(this).width($(this).parent().width());
});
$('.marquee').bind('beforeStarting',function () {
appBusy = true;
marqueeCounter++;
}).bind('finished', function () {
$(this).marquee('pause');
marqueeCounter--;
if (marqueeCounter < 1) {
appBusy = false;
}
}).marquee({
duration: 3500,
allowCss3Support: true,
duplicated: false
});
}
});
}
setTimeout(update, 5000);
}
The problem I am facing is that after hours of running this app, the marquees gradually slow down and eventually the browser (firefox) crashes.
Looking at the memory usage in firefox and chrome, the elements that are replaced with each $.ajax call don't seem to be freed from memory and the eventually choke the browser.
The DOM element count goes up and up as does memory usage.
I'm probably doing something fundamentally wrong here but cannot figure out how to free these resources up.
Thanks.
EDIT 1:
I have tried using the plugins destroy method as per the example on the developers page but it didn't help.
I have removed references to the plugin which results in the following code:
function update() {
if (appBusy == false) {
$.ajax({
url: '/get/html/from/server',
cache: false,
success: function (response) {
$('#div-container').empty();
$('#div-container').html(response);
}
});
}
setTimeout(update, 5000);
}
The number of nodes continues to grow and never decreases.
EDIT 2:
I have re-written this function in native javascript and the problem seems to have gone away.
function update()
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("div-container").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/get/html/from/server", true);
xmlhttp.send();
setTimeout(update, 5000);
}
Why would jQuery be returning different results?
This is an issue I'm facing only on Chrome.
Code snippets -
// Bind methods to global AJAX events
jQuery(document).bind({
ajaxStart : function() {
showWaitMessage(); // this is where it hangs
},
ajaxStop : function() {
hideWaitMessage();
},
ajaxError : function(jqXHR, exception) {
// error handling
}
});
The location redirect -
var href = "downloadPack?clientName="+clientName+"&clientID="+clientID+"&fundName="+fundName+"&fundID="+fundID+"&navDate="+navDate+"&KD="+KD+"&status="+status;
//setTimeout(function(){document.location.href = href;}, 500);
//window.location.href = href;
jQuery(location).attr('href', href); // Have tried the above two lines too (same issue)
The AJAX call -
function getExceptions() {
jQuery.ajax({url:"exceptions",success:function(result){
jQuery('#subApp').html(result);
document.getElementById("subLink1").className = "";
document.getElementById("subLink2").className = "selected";
document.getElementById("subLink3").className = "last_item";
if(jQuery("#fund").val() == 'all')
jQuery('#fund').val(jQuery('#fund option').filter(function() { return jQuery(this).html() == selectedFund;}).val());
jQuery('#fund option[value="all"]').prop('disabled', true);
getNavDates(0);
}});
}
The loaction redirect is not used to go to a different page, but to trigger a download.
This is when I face the problem in Chrome-
Click the download link(location redirect).
Call the AJAX function.
AJAX call hangs at showWaitMessage();
Download goes on as usual.
Note: Everything works fine on other browsers. The AJAX call on Chrome also works fine if I do that before hitting the download link.
There is a workaround for this problem – use hidden iframe for downloading instead of current window. Just define this simple function:
var $idown; // Keep it outside of the function, so it's initialized once.
function downloadURL(url) {
if ($idown) {
$idown.attr('src', url);
} else {
$idown = $('<iframe>', { id: 'idown', src: url }).hide().appendTo('body');
}
}
And replace your line:
jQuery(location).attr('href', href);
With:
downloadURL(href);
I am trying to check for the internet connection by sending a GET request to the server. I am a beginner in jquery and javascript. I am not using navigator.onLine for my code as it works differently in different browsers. This is my code so far:
var check_connectivity={
is_internet_connected : function(){
var dfd = new $.Deferred();
$.get("/app/check_connectivity/")
.done(function(resp){
return dfd.resolve();
})
.fail(function(resp){
return dfd.reject(resp);
})
return dfd.promise();
},
}
I call this code in different file as:
if(!this.internet_connected())
{
console.log("internet not connected");
//Perform actions
}
internet_connected : function(){
return check_connectivity.is_internet_connected();
},
The is_internet_connected() function returns a deferred object whereas I just need an answer in true/false. Can anybody tell me about how to achieve this?
$.get() returns a jqXHR object, which is promise compatible - therefore no need to create your own $.Deferred.
var check_connectivity = {
...
is_internet_connected: function() {
return $.get({
url: "/app/check_connectivity/",
dataType: 'text',
cache: false
});
},
...
};
Then :
check_connectivity.is_internet_connected().done(function() {
//The resource is accessible - you are **probably** online.
}).fail(function(jqXHR, textStatus, errorThrown) {
//Something went wrong. Test textStatus/errorThrown to find out what. You may be offline.
});
As you can see, it's not possible to be definitive about whether you are online or offline. All javascript/jQuery knows is whether a resource was successfully accessed or not.
In general, it is more useful to know whether a resource was successfully accessed (and that the response was cool) than to know about your online status per se. Every ajax call can (and should) have its own .done() and .fail() branches, allowing appropriate action to be taken whatever the outcome of the request.
Do you mean to check the internet connection if it's connected?
If so, try this:
$.ajax({
url: "url.php",
timeout: 10000,
error: function(jqXHR) {
if(jqXHR.status==0) {
alert(" fail to connect, please check your connection settings");
}
},
success: function() {
alert(" your connection is alright!");
}
});
100% Working:
function checkconnection() {
var status = navigator.onLine;
if (status) {
alert('Internet connected !!');
} else {
alert('No internet Connection !!');
}
}
This piece of code will continue monitoring internet connection
click bellow "Run code snippet" button and see it in action.
function checkInternetConnection(){
var status = navigator.onLine;
if (status) {
console.log('Internet Available !!');
} else {
console.log('No internet Available !!');
}
setTimeout(function() {
checkInternetConnection();
}, 1000);
}
//calling above function
checkInternetConnection();
try this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
if (! window.jQuery) {
alert('No internet Connection !!');
}
else {
// internet connected
}
Jquery Plugin for Detecting Internet Connection
you cannot get simple true or false in return, give them a callback handler
function is_internet_connected(callbackhandler)
{
$.get({
url: "/app/check_connectivity/",
success: function(){
callbackhandler(true);
},
error: function(){
callbackhandler(false);
},
dataType: 'text'
});
}
I just use the navigator onLine property, according to W3C http://www.w3schools.com/jsref/prop_nav_online.asp
BUT navigator only tells us if the browser has internet capability (connected to router, 3G or such).
So if this returns false you are probably offline but if it returns true you can still be offline if the network is down or really slow.
This is the time to check for an XHR request.
setInterval(setOnlineStatus(navigator.onLine), 10000);
function setOnlineStatus(online)
{
if (online) {
//Check host reachable only if connected to Router/Wifi/3G...etc
if (hostReachable())
$('#onlineStatus').html('ONLINE').removeAttr('class').addClass('online');
else
$('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
} else {
$('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
}
}
function hostReachable()
{
// Handle IE and more capable browsers
var xhr = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP");
var status;
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open("HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
// Issue request and handle response
try {
xhr.send();
return (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304));
} catch (error) {
return false;
}
}
EDIT: Use port number if it is different than 80, otherwise it fails.
xhr.open("HEAD", "//" + window.location.hostname + ":" + window.location.port + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
It's working fine for me.
<div id="status"></div>
<script>
window.addEventListener("offline", (event) => {
const statusDisplay = document.getElementById("status");
statusDisplay.textContent = "OFFline";
});
window.addEventListener("online", (event) => {
const statusDisplay = document.getElementById("status");
statusDisplay.textContent = "Online";
});
</script>
I have the code below to find the next sequential page number and load it at the bottom of the page once the user hits the bottom of the screen.
the loading div slides down and as it is loading and up once it is done... it is set to "display:none" by default
What i need is a line of code in there which basically hides the #loading div if no more pages can be found to load... " var url = "page"+nextpage+".html";" finds the new page... titled 'page 2.html, page3.html' and so on.
Any help would be appreciated. I'm assuming it is easy but I can't find a solution anywhere...
alreadyloading = false;
nextpage = 2;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
if (alreadyloading == false) {
$("#loading").slideDown();
var url = "page"+nextpage+".html";
alreadyloading = true;
$.post(url, function(data) {
$('#newcontent').children().last().after(data);
alreadyloading = false;
nextpage++;
$("#loading").slideUp();
});
}
}
});
If there is no such file then the AJAX request will fail, so you can do what you need from inside a "failure" handler. To be able to specify that, you one solution is to move from using $.post to using the more configurable $.ajax, which gives you all the necessary options:
$.ajax({
type: 'POST',
url: url,
success: function(data) {
$('#newcontent').children().last().after(data);
nextpage++;
},
complete: function() {
alreadyloading = false;
$("#loading").slideUp();
}
});
The complete callback contains code which will be executed no matter what happens with the request; the success callback will be executed before complete, but only if the request was successful.
I have a link: Hello.
When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect to another URL.
It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work – browser security prevents cross-domain calls (the same-origin policy).
If it is on the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax() method does – the $.ajax() method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499). Example:
$.ajax({
type: 'HEAD',
url: 'http://yoursite.com/page.html',
success: function() {
// page exists
},
error: function() {
// page does not exist
}
});
See also: http://api.jquery.com/jQuery.ajax/
A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/
From there you can do something like: select * from htmlstring where url="http://google.com". You can use the "REST query" they have on that page as a starting point for your code.
Here's some code that would accept a full URL and use YQL to detect if that page exists:
function isURLReal(fullyQualifiedURL) {
var URL = encodeURIComponent(fullyQualifiedURL),
dfd = $.Deferred(),
checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22' + URL + '%22&format=json');
checkURLPromise
.done(function(response) {
// results should be null if the page 404s or the domain doesn't work
if (response.query.results) {
dfd.resolve(true);
} else {
dfd.reject(false);
}
})
.fail(function() {
dfd.reject('failed');
});
return dfd.promise();
}
// usage
isURLReal('http://google.com')
.done(function(result) {
// yes, or request succeded
})
.fail(function(result) {
// no, or request failed
});
Update August 2nd, 2017
It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.
Based on the documentation for XMLHttpRequest:
function returnStatus(req, status) {
//console.log(req);
if(status == 200) {
console.log("The url is available");
// send an event
}
else {
console.log("The url returned status code " + status);
// send a different event
}
}
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this, this.status);
}
client.open("HEAD", address);
client.send();
}
fetchStatus("/");
This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.
If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.
If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.
why not just create a custom 404 handler on the web server? this is probably the more "good-bear" way to do this.
$.ajax({
url: "http://something/whatever.docx",
method: "HEAD",
statusCode: {
404: function () {
alert('not found');
},
200: function() {
alert("foundfile exists");
}
}
});
If you are happy to use jQuery you could do something like this.
When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
<!--
$.fn.checkPageExists = function(defaultUrl){
$.each(this, function(){
var $link = $(this);
$.ajax({
url: $link.attr("href"),
error: function(){
$link.attr("href", defaultUrl);
}
});
});
};
$(document).ready(function(){
$("a").checkPageExists("default.html");
});
//-->
</script>
You won't be able to use an ajax call to ping the website because of same-origin policy.
The best way to do it is to use an image and if you know the website you are calling has a favicon or some sort of icon to grab, you can just use an html image tag and use the onerror event.
Example:
function pingImgOnWebsite(url) {
var img = document.createElement('img');
img.style.visibility = 'hidden';
img.style.position = 'fixed';
img.src = url;
img.onerror = continueBtn; // What to do on error function
document.body.appendChild(img);
}
Another way to do this is is with PHP.
You could add
<?php
if (file_exists('/index.php'))
{
$url = '/index.php';
} else {
$url = '/notindex.php';
}
?>
And then
<a href="<?php echo $url; ?>Link</a>