Check Internet connectivity with jquery - javascript

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>

Related

Freeing DOM element memory / resources created by ajax request

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?

Callback function doesn't work in firefox

I'm writting web client for my Exchange Server and I have problem. One of the functions responsible for the getting a current state of user wallet. But after receive answer from server the callback function doesn't work (only in firefox). In Chrome, Opera and Safari it's working good without problem. I'm sure than the problem is on the client side becouse server send completely data.
Code of my function :
proto.on("login", function(status, settings) {
user.waluta = user.currency(settings.waluta);
user.session = settings.idSesja;
proto.getWallet(settings.idSesja, settings.waluta, function(result){
setUserWallet(result);
});
window.location.reload();
});
And code of "getWallet" :
self.getWallet = function(sesja, waluta, callback, successCallback, failureCallback) {
if (self.isConnected()) {
var ses = {
'#class': 'event.IDSesji',
'idSesji': sesja,
'login': self.username
};
self.socket.json.emit('dajPortfel', {
'#class': 'event.DajPortfel',
'waluta': waluta,
'sesja': ses
}, function(data) {
if (data.kod == ResultStatus.ok) {
callback(data.zalacznik);
if (isFunc(successCallback)) successCallback(data.zalacznik);
} else {
if (isFunc(failureCallback)) failureCallback(data.kod);
}
});
} else {
if (isFunc(jobDoneHandler)) { jobDoneHandler(ResultStatus.notConnected); }
}
}

If iframe refresh failed, then X

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>

checking the page exist or not using javascript [duplicate]

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>

Simple AJAX request using jQuery not working on IE

This is my code, which sometimes works and sometimes doesn't.
var resolve_ajax_login=function(){
$.ajaxSetup({cache:false });
var loginvar=$("#inputlogin").attr("value");
var senhavar=$("#inputsenha").attr("value");
$.post("../model/php/login_ajax.php",
{login:loginvar, senha:senhavar},
function(responseText){
if (responseText=="ok"){
window.location="areatrab.php";
}else{
$("#inputlogin").attr("value","");
$("#inputsenha").attr("value","");
$("#divmensagem").html("<span style='color:red;font-size:70%;'>"+responseText+"</span>");
}
}
);
return false;
};
Ok. It's in portuguese but I think you get the general picture. Sometimes this works, no problem, but some other times (only in IE, no problem whatsoever in Firefox) it throws a javascript error in my jquery.js file (minified). The error description is as follows:
Object doesn't support this property or method: jquerymin.js line 123 character 183..
which amounts to...
{return new A.XMLHttpRequest}
somewhere in the middle of the jquery.js file. It seems to be very IE-specific, as I had no such problems on Firefox. This guy apparently had the same problem as I did, but got no responses yet.
Has anyone else seen this? Thanks in Advance
P.S.: I run IE 8
Have you tried using a full URL instead of ../model...? For example: http://www.mysite.com/model/login_ajax.php
Also, maybe try modifying the 'xhr' property using jQuery's .ajax method... something like:
var loginvar = $("#inputlogin").val();
var senhavar = $("#inputsenha").val();
var ajax_obj = null;
var resolve_ajax_login = function() {
if(ajax_obj !== null) {
try {
ajax_obj.abort();
} catch(e) {
}
}
ajax_obj = $.ajax({
type: 'POST',
cache: false,
url: '../model/php/login_ajax.php',
data: {login:loginvar, senha:senhavar},
dataType: 'text',
timeout: 7000,
success: function(data)
{
if(response == 'ok') {
alert("right on!");
} else {
alert("not ok");
return;
}
},
error: function(req, reqStatus, reqError)
{
alert("error");
return;
},
'xhr': function() {
if(ajax_obj !== null) {
return ajax_obj;
}
if($.browser.msie && $.browser.version.substr(0,1) <= 7) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
return new XMLHttpRequest();
}
}
});
}
It's something to do with the order in which you try all the different types of browsers in order to create the right kind of XMLHTTP REQUEST object.. I'll explain it in more detail in the following page:
AJAX inconsistency in IE 8?

Categories

Resources