AJAX polling and looping - javascript

My project is basically like a Reddit feed that updates in real-time. I'm trying to use AJAX to poll the server at intervals for updates on 15 items at a time.
I wrote a for loop but it caused the browser to lock up (I'm guessing too many XHRs?).
How can I poll each item on the Reddit-esque feed without locking up the browser? What is the most efficient way to do this?
Should I use long-polling if there are 100+ clients using the web app at the same time? Or should I opt for smart polling (increasing the wait time between requests if no data)?
Thanks! I'm still new to AJAX!
for (var i=0; i < id_array_len; i++) {
// Grab current reply count
var reply = $("#repl"+item_id).html();
var url= *php function here*
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser does not support AJAX!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readystate == 4){
live_feed_data_tot = ajaxRequest.responseText;
if (live_feed_data_tot.trim() == "no change" || live_feed_data_tot.trim() == "no meme" || live_feed_data_tot.trim() == "no response"){
console.log("(no update)");
} else {
var live_feed_data = live_feed_data_tot.split(',');
if (live_feed_data[1] == 'reply') {
// Reply count has changed
new_reply = live_feed_data[0].trim();
// Update actual number
$("#repl"+item_id).html(new_reply);
}
}
}
}
ajaxRequest.open('POST', url, true);
ajaxRequest.send();

Use longpolling with a long (appropriate for your app of course) timeout. Your call needs to be asynchronous of course. As long as there is no data to deliver, the server holds the answer back, until the timeout is about to be reached. As soon as the client gets an answer, trigger the next longpoll in your complete()-Block. This way you can minimize the number of requests.
EDIT: after seeing your code i see you use native ajax but use jQuery for selecting. I suggest you to use jQuery for your ajax requests as well (jQuery .ajax() Doku).
Your code should look something like this:
function doAjaxLongpollingCall(){
$.ajax({
url: "...",
timeout: <prettylong>,
success: function(){
//process your data
},
complete: function(){
doAjaxLongpollingCall();
}
});
}

If you are doing a lot of users, switch to socket.io and save yourself the hassle. It uses websockets (which use a push mechanism) and does fallbacks to other mechanisms like flash sockets or long polling if thats not available in the browser. Requires you to create this piece of your app in node.js though.

Related

Different types of ajax implementation

i have just started working on ajax for my chat application which i am making in php.
While studying ajax online I cam across 2 ways in on different sites where ajax had been implemented.
What is the difference between these 2 implementations of ajax?
Any help will be greatly appreciated :)
First Implementation-
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat.php',
data: {dept:dept},
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
</script>
Second Implementation-
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
Functionality-wise, it could be argued that there is no difference between them.
That said, the first "difference" between them is that the first method is using JQuery, and thus to use it, you need to have the JQuery Javascript library included in your project or the page where you need the ajax functionality. The second method, however, uses "plain ole Javascript".
Again, the first (JQuery) method, handles a lot of the "dirty" details for you, providing you with an ($.ajax) interface and requiring only that you pass in some parameters:
url : The URL you wish to call
data : The data (GET or POST) you wish to pass to the URL
success : The callback function that should be executed when the ajax request successfully returns.
In doing this, this method abstracts the internal implementation from you. For example, it handles for you the following:
browser-sniffing/capabilities detection
readyStateChange (event) checks
and some other mundane details.
Besides, also, using the second method, you can rest-assured that your code will mostly work in the majority of scenarios (if not all), if you "honour" the interface specification of the $.ajax call. Using the second method, however, you'll need to do a lot of testing and checks to ensure that your code works across all browser and platform types.
Your first code use jQuery. JQuery is a rich js lib that helps you coding quickly. See http://api.jquery.com/ (and in your particular case : http://api.jquery.com/jQuery.ajax/
Your second code is only javascript without any help from other library. It uses the XMLHttpRequest wich allows ajax call. See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
The use of jQuery is easier but some find it "overkill" :)

How to check if the user is online using javascript or any library?

I need some help on how I could check the internet connection using Javascript or jQuery or any library if available. cause i'm developing an offline application and I want to show a version if the user is offline and another version if the user is online.
For the moment i'm using this code :
if (navigator.onLine) {
alert('online');
} else {
alert('offline');
}
But this is working very slow to detect. sometimes it's just connected to a network without internet, it takes 5 to 10 seconds to alert false (No internet).
I took a look at Offline.js library, but I'm not sure if this library is useful in my case. and I don't know how to use it
I just got this bit of code functionality from a Mozilla Site:
window.addEventListener('load', function(e) {
if (navigator.onLine) {
console.log('We\'re online!');
} else {
console.log('We\'re offline...');
}
}, false);
window.addEventListener('online', function(e) {
console.log('And we\'re back :).');
}, false);
window.addEventListener('offline', function(e) {
console.log('Connection is down.');
}, false);
They even have a link to see it working. I tried it in IE, Firefox and Chrome. Chrome appeared the slowest but it was only about half a second.
i think you should try OFFLINE.js.. it looks pretty easy to use, just give it a try.
it even provides the option checkOnLoad which checks the connection immediately on page load.
Offline.check(): Check the current status of the connection.
Offline.state: The current state of the connection 'up' or 'down'
haven't tried it, would be nice to know if it works as intended.
EDIT took a little peak into the code, it uses the method with FAILED XHR REQUEST suggested in THIS SO Question
Take a look at Detect that the Internet connection is offline? Basically, make an ajax request to something you know is likely to be up (say google.com) and if it fails, there is no internet connection.
navigator.onLine is a property that maintains a true/false value (true for online, false for offline). This property is updated whenever the user switches into "Offline Mode".
window.addEventListener('load', function() {
function updateOnlineStatus(event) {
document.body.setAttribute("data-online", navigator.onLine);
}
updateOnlineStatus();
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
});
// check if online/offline
// http://www.kirupa.com/html5/check_if_internet_connection_exists_in_javascript.htm
function doesConnectionExist() {
var xhr = new XMLHttpRequest();
var file = "http://www.yoursite.com/somefile.png";
var randomNum = Math.round(Math.random() * 10000);
xhr.open('HEAD', file + "?rand=" + randomNum, false);
try {
xhr.send();
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e) {
return false;
}
}
My solution is to grab a very small image (1x1), not cached and always onLine.
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<script>
$( document ).ready(function() {
function onLine() {
alert("onLine")
}
function offLine() {
alert("offLine")
}
var i = new Image();
i.onload = onLine;
i.onerror = offLine;
i.src = 'http://www.google-analytics.com/__utm.gif';
});
</script>
<body>
Notes:
Use a local copy of jQuery otherwise it won't work offLine.
I've tested the code onLine/offLine and it works without delay.
Works with all browsers, Desktop or Mobile.
In case you wonder, there's no tracking made from Google Analytics as we don't use any arguments.
Feel free to change the image, just make sure it doesn't get cached and it's small in size.
Try utilizing WebRTC , see diafygi/webrtc-ips; in part
Additionally, these STUN requests are made outside of the normal
XMLHttpRequest procedure, so they are not visible in the developer
console or able to be blocked by plugins such as AdBlockPlus or
Ghostery. This makes these types of requests available for online
tracking if an advertiser sets up a STUN server with a wildcard
domain.
modified minimally to log "online" or "offline" at console
// https://github.com/diafygi/webrtc-ips
function online(callback){
//compatibility for firefox and chrome
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
//bypass naive webrtc blocking using an iframe
if(!RTCPeerConnection) {
//NOTE: you need to have an iframe in the page
// right above the script tag
//
//<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
//<script>...getIPs called in here...
//
var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection
|| win.mozRTCPeerConnection
|| win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
//minimal requirements for data connection
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};
//firefox already has a default stun server in about:config
// media.peerconnection.default_iceservers =
// [{"url": "stun:stun.services.mozilla.com"}]
var servers = undefined;
//add same stun server for chrome
if(useWebKit)
servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);
//create a bogus data channel
pc.createDataChannel("");
var fn = function() {};
//create an offer sdp
pc.createOffer(function(result){
//trigger the stun server request
pc.setLocalDescription(result, fn, fn);
}, fn);
//wait for a while to let everything done
setTimeout(function(){
//read candidate info from local description
var lines = pc.localDescription.sdp.split("\n");
// return `true`:"online" , or `false`:"offline"
var res = lines.some(function(line) {
return line.indexOf("a=candidate") === 0
});
callback(res);
}, 500);
}
//Test: Print "online" or "offline" into the console
online(function(connection) {
if (connection) {
console.log("online")
} else {
console.log("offline")
}
});
You can use SignalR, if you're developing using MS web technologies. SignalR will establish either long polling or web sockets depending on your server/client browser technology, transparent to you the developer. You don't need to use it for anything else than determining if you have an active connection to the site or not.
If SignalR disconnects for any reason, then you have lost connection to the site, as long as your SignalR server instance is actually installed on the site. Thus, you can use $.connection.hub.disconnected() event/method on the client to set a global var which holds your connection status.
Read up about SignalR and how to use it for determining connection states here...
http://www.asp.net/signalr/overview/guide-to-the-api/handling-connection-lifetime-events#clientdisconnect
See How do I check connection type (WiFi/LAN/WWAN) using HTML5/JavaScript? answers:
Rob W suggests navigator.connection;
Bergi suggests Windows.Networking.Connectivity API through this tutorial;
Gerard Sexton suggests Gmail approach.
You can use the new Fetch API which will trigger an error almost immediately if no network is present.
The problem with this is that the Fetch API has infant support at the moment (currently Chrome has the most stable implementation, Firefox and Opera is getting there, IE does not support it). There exists a polyfill to support the fetch principle but not necessarily the rapid return as with a pure implementation. On the other hand, an offline app would require a modern browser...
An example which will try to load a plain text file over HTTPS to avoid CORS requirements (link is picked at random, you should set up a server with a tiny text file to test against - test in Chrome, for now):
fetch("https://link.to/some/testfile")
.then(function(response) {
if (response.status !== 200) { // add more checks here, ie. 30x etc.
alert("Not available"); // could be server errors
}
else
alert("OK");
})
.catch(function(err) {
alert("No network"); // likely network errors (incl. no connection)
});
Another option is to set up a Service worker and use fetch from there. This way you could serve an optional/custom offline page or a cached page when the requested page is not available. Also this is a very fresh API.
best one liner
console.log(navigator.onLine ? 'online' : 'offline');

php not returning any result to javascript ajax object

I'm trying to use ajax, I've used it before, copied the code from my previous html file and altered the values sent, php file to process the code and I'm using the POST method. However, the php script does not return anything to the html page. I've checked all i can, so I'm here now.
function look () {
var x = document.getElementsByTagName('option')[document.getElementById("region").selectedIndex].value;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// modal section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("accordion");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
ajaxRequest.open("POST", "search.php", true);
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
alert(x);
ajaxRequest.send("region=" + x);
}
The php code is a simple
<?php
echo "The world is blue.";
?>
yet, it returns nothing to the chosen div.
You've probably not posted enough information for us to answer your question. But, I acknowledge that you probably are not sure what questions you need to ask in the first place.
First, I must agree with #cgf. jQuery or the alike will make this easier.
But lets focus on the problem at hand. We need to know what is happening behind the scenes.
The best way to do this is through a developer tool bar such as firebug. Chrome has one built in.
So, load up chrome and hit F12. This should bring up a very busy looking pane on the bottom of your window. Select the Network tab and then request your page / trigger your javascript. What output do you get in the network tab? Mainly, under status do you get 200, 500 (server error) or perhaps 404 (not found)? Update your question above with what you see / get.
My hope is that this should point you in the right direction.

How to detect online/offline event cross-browser?

I'm trying to accurately detect when the browser goes offline, using the HTML5 online and offline events.
Here's my code:
<script>
// FIREFOX
$(window).bind("online", applicationBackOnline);
$(window).bind("offline", applicationOffline);
//IE
window.onload = function() {
document.body.ononline = IeConnectionEvent;
document.body.onoffline = IeConnectionEvent;
}
</script>
It works fine when I just hit "Work offline" on either Firefox or IE, but it's kind of randomly working when I actually unplug the wire.
What's the best way to detect this change? I'd like to avoid repeating ajax calls with timeouts.
Currently in 2011, the various browser vendors cannot agree on how to define offline. Some browsers have a Work Offline feature, which they consider separate to a lack of network access, which again is different to internet access. The whole thing is a mess. Some browser vendors update the navigator.onLine flag when actual network access is lost, others don't.
From the spec:
Returns false if the user agent is
definitely offline (disconnected from
the network). Returns true if the user
agent might be online.
The events online and offline are
fired when the value of this attribute
changes.
The navigator.onLine attribute must
return false if the user agent will
not contact the network when the user
follows links or when a script
requests a remote page (or knows that
such an attempt would fail), and must
return true otherwise.
Finally, the spec notes:
This attribute is inherently
unreliable. A computer can be
connected to a network without having
Internet access.
The major browser vendors differ on what "offline" means.
Chrome, Safari, and Firefox (since version 41) will detect when you go "offline" automatically - meaning that "online" events and properties will fire automatically when you unplug your network cable.
Mozilla Firefox (before version 41), Opera, and IE take a different approach, and consider you "online" unless you explicitly pick "Offline Mode" in the browser - even if you don't have a working network connection.
There are valid arguments for the Firefox/Mozilla behavior, which are outlined in the comments of this bug report:
https://bugzilla.mozilla.org/show_bug.cgi?id=654579
But, to answer the question - you can't rely on the online/offline events/property to detect if there is actually network connectivity.
Instead, you must use alternate approaches.
The "Notes" section of this Mozilla Developer article provides links to two alternate methods:
https://developer.mozilla.org/en/Online_and_offline_events
"If the API isn't implemented in the browser, you can use other signals to detect if you are offline including listening for AppCache error events and responses from XMLHttpRequest"
This links to an example of the "listening for AppCache error events" approach:
http://www.html5rocks.com/en/mobile/workingoffthegrid/#toc-appcache
...and an example of the "listening for XMLHttpRequest failures" approach:
http://www.html5rocks.com/en/mobile/workingoffthegrid/#toc-xml-http-request
HTH,
-- Chad
Today there's an open source JavaScript library that does this job: it's called Offline.js.
Automatically display online/offline indication to your users.
https://github.com/HubSpot/offline
Be sure to check the full README. It contains events that you can hook into.
Here's a test page. It's beautiful/has a nice feedback UI by the way! :)
Offline.js Simulate UI is an Offline.js plug-in
that allows you to test how your pages respond to different
connectivity states without having to use brute-force methods to
disable your actual connectivity.
The best way which works now on all Major Browsers is the following Script:
(function () {
var displayOnlineStatus = document.getElementById("online-status"),
isOnline = function () {
displayOnlineStatus.innerHTML = "Online";
displayOnlineStatus.className = "online";
},
isOffline = function () {
displayOnlineStatus.innerHTML = "Offline";
displayOnlineStatus.className = "offline";
};
if (window.addEventListener) {
/*
Works well in Firefox and Opera with the
Work Offline option in the File menu.
Pulling the ethernet cable doesn't seem to trigger it.
Later Google Chrome and Safari seem to trigger it well
*/
window.addEventListener("online", isOnline, false);
window.addEventListener("offline", isOffline, false);
}
else {
/*
Works in IE with the Work Offline option in the
File menu and pulling the ethernet cable
*/
document.body.ononline = isOnline;
document.body.onoffline = isOffline;
}
})();
Source: http://robertnyman.com/html5/offline/online-offline-events.html
Since recently, navigator.onLine shows the same on all major browsers, and is thus useable.
if (navigator.onLine) {
// do things that need connection
} else {
// do things that don't need connection
}
The oldest versions that support this in the right way are: Firefox 41, IE 9, Chrome 14 and Safari 5.
Currently this will represent almost the whole spectrum of users, but you should always check what the users of your page have of capabilities.
Previous to FF 41, it would only show false if the user put the browser manually in offline mode. In IE 8, the property was on the body, instead of window.
source: caniuse
The window.navigator.onLine attribute and its associated events are currently unreliable on certain web browsers (especially Firefox desktop) as #Junto said, so I wrote a little function (using jQuery) that periodically checks the network connectivity status and raise the appropriate offline and online events:
// Global variable somewhere in your app to replicate the
// window.navigator.onLine variable (this last is not modifiable). It prevents
// the offline and online events to be triggered if the network
// connectivity is not changed
var IS_ONLINE = true;
function checkNetwork() {
$.ajax({
// Empty file in the root of your public vhost
url: '/networkcheck.txt',
// We don't need to fetch the content (I think this can lower
// the server's resources needed to send the HTTP response a bit)
type: 'HEAD',
cache: false, // Needed for HEAD HTTP requests
timeout: 2000, // 2 seconds
success: function() {
if (!IS_ONLINE) { // If we were offline
IS_ONLINE = true; // We are now online
$(window).trigger('online'); // Raise the online event
}
},
error: function(jqXHR) {
if (jqXHR.status == 0 && IS_ONLINE) {
// We were online and there is no more network connection
IS_ONLINE = false; // We are now offline
$(window).trigger('offline'); // Raise the offline event
} else if (jqXHR.status != 0 && !IS_ONLINE) {
// All other errors (404, 500, etc) means that the server responded,
// which means that there are network connectivity
IS_ONLINE = true; // We are now online
$(window).trigger('online'); // Raise the online event
}
}
});
}
You can use it like this:
// Hack to use the checkNetwork() function only on Firefox
// (http://stackoverflow.com/questions/5698810/detect-firefox-browser-with-jquery/9238538#9238538)
// (But it may be too restrictive regarding other browser
// who does not properly support online / offline events)
if (!(window.mozInnerScreenX == null)) {
window.setInterval(checkNetwork, 30000); // Check the network every 30 seconds
}
To listen to the offline and online events (with the help of jQuery):
$(window).bind('online offline', function(e) {
if (!IS_ONLINE || !window.navigator.onLine) {
alert('We have a situation here');
} else {
alert('Battlestation connected');
}
});
navigator.onLine is a mess
I face this when trying to make an ajax call to the server.
There are several possible situations when the client is offline:
the ajax call timouts and you receive error
the ajax call returns success, but the msg is null
the ajax call is not executed because browser decides so (may be this is when navigator.onLine becomes false after a while)
The solution I am using is to control the status myself with javascript. I set the condition of a successful call, in any other case I assume the client is offline.
Something like this:
var offline;
pendingItems.push(item);//add another item for processing
updatePendingInterval = setInterval("tryUpdatePending()",30000);
tryUpdatePending();
function tryUpdatePending() {
offline = setTimeout("$('#offline').show()", 10000);
$.ajax({ data: JSON.stringify({ items: pendingItems }), url: "WebMethods.aspx/UpdatePendingItems", type: "POST", dataType: "json", contentType: "application/json; charset=utf-8",
success: function (msg) {
if ((!msg) || msg.d != "ok")
return;
pending = new Array(); //empty the pending array
$('#offline').hide();
clearTimeout(offline);
clearInterval(updatePendingInterval);
}
});
}
In HTML5 you can use the navigator.onLine property. Look here:
http://www.w3.org/TR/offline-webapps/#related
Probably your current behavior is random as the javascript only ready the "browser" variable and then knows if you're offline and online, but it doesn't actually check the Network Connection.
Let us know if this is what you're looking for.
Kind Regards,
Please find the require.js module that I wrote for Offline.
define(['offline'], function (Offline) {
//Tested with Chrome and IE11 Latest Versions as of 20140412
//Offline.js - http://github.hubspot.com/offline/
//Offline.js is a library to automatically alert your users
//when they've lost internet connectivity, like Gmail.
//It captures AJAX requests which were made while the connection
//was down, and remakes them when it's back up, so your app
//reacts perfectly.
//It has a number of beautiful themes and requires no configuration.
//Object that will be exposed to the outside world. (Revealing Module Pattern)
var OfflineDetector = {};
//Flag indicating current network status.
var isOffline = false;
//Configuration Options for Offline.js
Offline.options = {
checks: {
xhr: {
//By default Offline.js queries favicon.ico.
//Change this to hit a service that simply returns a 204.
url: 'favicon.ico'
}
},
checkOnLoad: true,
interceptRequests: true,
reconnect: true,
requests: true,
game: false
};
//Offline.js raises the 'up' event when it is able to reach
//the server indicating that connection is up.
Offline.on('up', function () {
isOffline = false;
});
//Offline.js raises the 'down' event when it is unable to reach
//the server indicating that connection is down.
Offline.on('down', function () {
isOffline = true;
});
//Expose Offline.js instance for outside world!
OfflineDetector.Offline = Offline;
//OfflineDetector.isOffline() method returns the current status.
OfflineDetector.isOffline = function () {
return isOffline;
};
//start() method contains functionality to repeatedly
//invoke check() method of Offline.js.
//This repeated call helps in detecting the status.
OfflineDetector.start = function () {
var checkOfflineStatus = function () {
Offline.check();
};
setInterval(checkOfflineStatus, 3000);
};
//Start OfflineDetector
OfflineDetector.start();
return OfflineDetector;
});
Please read this blog post and let me know your thoughts. http://zen-and-art-of-programming.blogspot.com/2014/04/html-5-offline-application-development.html It contains a code sample using offline.js to detect when the client is offline.
you can detect offline cross-browser way easily like below
var randomValue = Math.floor((1 + Math.random()) * 0x10000)
$.ajax({
type: "HEAD",
url: "http://yoururl.com?rand=" + randomValue,
contentType: "application/json",
error: function(response) { return response.status == 0; },
success: function() { return true; }
});
you can replace yoururl.com by document.location.pathname.
The crux of the solution is, try to connect to your domain name, if you are not able to connect - you are offline. works cross browser.
I use the FALLBACK option in the HTML5 cache manifest to check if my html5 app is online or offline by:
FALLBACK:
/online.txt /offline.txt
In the html page i use javascript tot read the contents of the online/offline txt file:
<script>$.get( "urlto/online.txt", function( data ) {
$( ".result" ).html( data );
alert( data );
});</script>
When offline the script will read the contents of the offline.txt.
Based on the text in the files you can detect if the webpage is online of offline.
Using Document Body:
<body ononline="onlineConditions()" onoffline="offlineConditions()">(...)</body>
Using Javascript Event:
window.addEventListener('load', function() {
function updateOnlineStatus() {
var condition = navigator.onLine ? "online" : "offline";
if( condition == 'online' ){
console.log( 'condition: online')
}else{
console.log( 'condition: offline')
}
}
window.addEventListener('online', updateOnlineStatus );
window.addEventListener('offline', updateOnlineStatus );
});
Reference:
Document-Body: ononline Event
Javascript-Event: Online and offline events
Additional Thoughts:
To ship around the "network connection is not the same as internet connection" Problem from the above methods: You can check the internet connection once with ajax on the application start and configure an online/offline mode. Create a reconnect button for the user to go online. And add on each failed ajax request a function that kick the user back into the offline mode.
Here is my solution.
Tested with IE, Opera, Chrome, FireFox, Safari, as Phonegap WebApp on IOS 8 and as Phonegap WebApp on Android 4.4.2
This solution isn't working with FireFox on localhost.
=================================================================================
onlineCheck.js (filepath: "root/js/onlineCheck.js ):
var isApp = false;
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
isApp = true;
}
function isOnlineTest() {
alert(checkOnline());
}
function isBrowserOnline(no,yes){
//Didnt work local
//Need "firefox.php" in root dictionary
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
if(yes instanceof Function){
yes();
}
}
xhr.onerror = function(){
if(no instanceof Function){
no();
}
}
xhr.open("GET","checkOnline.php",true);
xhr.send();
}
function checkOnline(){
if(isApp)
{
var xhr = new XMLHttpRequest();
var file = "http://dexheimer.cc/apps/kartei/neu/dot.png";
try {
xhr.open('HEAD', file , false);
xhr.send(null);
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e)
{
return false;
}
}else
{
var tmpIsOnline = false;
tmpIsOnline = navigator.onLine;
if(tmpIsOnline || tmpIsOnline == "undefined")
{
try{
//Didnt work local
//Need "firefox.php" in root dictionary
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
tmpIsOnline = true;
}
xhr.onerror = function(){
tmpIsOnline = false;
}
xhr.open("GET","checkOnline.php",false);
xhr.send();
}catch (e){
tmpIsOnline = false;
}
}
return tmpIsOnline;
}
}
=================================================================================
index.html (filepath: "root/index.html"):
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="js/onlineCheck.js" ></script>
...
</head>
...
<body onload="onLoad()">
...
<div onclick="isOnlineTest()">
Online?
</div>
...
</body>
</html>
=================================================================================
checkOnline.php (filepath: "root"):
<?php echo 'true'; ?>
well, you can try the javascript plugin which can monitor the browser connection in real time and notifies the user if internet or the browsers connection with the internet went down.
Wiremonkey Javascript plugin
and the demo you can find here
http://ryvan-js.github.io/
<html>
<head>
<script>
window.addEventListener("online",function(){
document.getElementById('note').
innerHTML='you are online';
});
window.addEventListener("offline",function(){
document.getElementById('note').
innerHTML='you are offline';
});
</script>
</head>
<body>
<div id="note"> </div>
</body>
</html>

Cross-browser implementation of "HTTP Streaming" (push) AJAX pattern

Client request web page from server. Clent then requests for extra calculations to be done; server performs series of calculations and sends partial results as soon as they are available (text format, each line contains separate full item). Client updates web page (with JavaScript and DOM) using information provided by server.
This seems to fit HTTP Streaming (current version) pattern from Ajaxpatterns site.
The question is how to do it in cross-browser (browser agnostic) way, preferably without using JavaScript frameworks, or using some lightweight framework like jQuery.
The problem begins with generating XMLHttpRequest in cross-browser fashion, but I think the main item is that not all browsers implement correctly onreadystatechangefrom XMLHttpRequest; not all browsers call onreadystatechange event on each server flush (BTW. how to force server flush from within CGI script (in Perl)?). Example code on Ajaxpatterns deals with this by using timer; should I drop timer solution if I detect partial response from onreadystatechange?
Added 11-08-2009
Current solution:
I use the following function to create XMLHttpRequest object:
function createRequestObject() {
var ro;
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
} else {
ro = new ActiveXObject("Microsoft.XMLHTTP");
}
if (!ro)
debug("Couldn't start XMLHttpRequest object");
return ro;
}
If I were to use some (preferably light-weight) JavaScript framework like jQuery, I'd like to have fallback if user chooses not to install jQuery.
I use the following code to start AJAX; setInterval is used because some browsers call onreadystatechange only after server closes connection (which can take as long as tens of seconds), and not as soon as server flushes data (around every second or more often).
function startProcess(dataUrl) {
http = createRequestObject();
http.open('get', dataUrl);
http.onreadystatechange = handleResponse;
http.send(null);
pollTimer = setInterval(handleResponse, 1000);
}
The handleResponse function is most complicated one, but the sketch of it looks like the following. Can it be done better? How it would be done using some lightweight JavaScript framework (like jQuery)?
function handleResponse() {
if (http.readyState != 4 && http.readyState != 3)
return;
if (http.readyState == 3 && http.status != 200)
return;
if (http.readyState == 4 && http.status != 200) {
clearInterval(pollTimer);
inProgress = false;
}
// In konqueror http.responseText is sometimes null here...
if (http.responseText === null)
return;
while (prevDataLength != http.responseText.length) {
if (http.readyState == 4 && prevDataLength == http.responseText.length)
break;
prevDataLength = http.responseText.length;
var response = http.responseText.substring(nextLine);
var lines = response.split('\n');
nextLine = nextLine + response.lastIndexOf('\n') + 1;
if (response[response.length-1] != '\n')
lines.pop();
for (var i = 0; i < lines.length; i++) {
// ...
}
}
if (http.readyState == 4 && prevDataLength == http.responseText.length)
clearInterval(pollTimer);
inProgress = false;
}
The solution you linked to is not AJAX at all, actually. They call it HTTP Streaming but it's essentially just long polling.
In the example they link to, you can see for yourself quite easily with firebug. Turn on the Net panel - there are no XHR entries, but it takes just a hair over 10 seconds to load the original page. That's because they're using PHP behind the scenes to delay the output of the HTML. This is the essence of long polling - the HTTP connection stays open, and the periodic HTML sent back is javascript commands.
You can opt to do the polling completely on the client side, though, with setTimeout() or setInterval()
A jQuery example
<script type="text/javascript">
$(document).ready(function()
{
var ajaxInterval = setInterval( function()
{
$.getJSON(
'some/servie/url.ext'
, { sample: "data" }
, function( response )
{
$('#output').append( response.whatever );
}
);
}, 10000 );
});
</script>
I would take a look at orbited
They use several comet transport implementation that they choose based on configuration and browser sniffing.
See http://orbited.org/svn/orbited/trunk/daemon/orbited/static/Orbited.js
and look for "Orbited.CometTransports"
Some of the different transports must be matched by the backend implementation, so have a look at the server side for orbited also.

Categories

Resources