What is the best way to check your internet connection?

I created a CMS that retrieves large amounts of data during an operation. CMS is created in PHP, MySQL, jQuery, Bootstrap and uses AJAX.

The problem is that if you lose your Internet connection, it can cause problems when displaying and scrolling.

I would really like it if there is a good way to show an error and block all functions on the site when there is no Internet connection. When the connection is established, everything should be allowed on the site.

Thank!

(Sorry for my bad English.)

+3
source share
3 answers

jQuery, . .

$( document ).ajaxError(function() {
  // lock your UI here
});

, , , Exponential Backoff .

jQuery blockUI.

(function ($) {
  var locked = false;
  var errorRetryCount = 0;
  var blockUiOptions = { message: "Oops! Could not reach the server!" };

  // change this function to adjust the exponential backoff delay
  function backoff(n) {
    return Math.pow(2, n) * 100;
  }

  $(function () {
    $( document ).ajaxError(function () {
      var req = this;

      errorRetryCount += 1;

      if (!locked) {
         locked = true;
         $.blockUI(blockUiOptions);
      }

      // retry to send the request...
      setTimeout(function () { $.ajax(req); }, backoff(errorRetryCount));
    }).ajaxSuccess(function () {
      locked && $.unblockUI();
      locked = false;
      errorRetryCount = 0;
    });
  });
})(jQuery);

. , - . , . , .

+2

jQuery, - , , - - .

- :

setInterval(function() {
  $.ajax({
    url: "https://cms.example.com/ping",
  })
  .fail(function( data ) {
    alert('Connection lost?');
    // remember do to something smart which shows the error just once
    // instead of every five seconds. Increasing the interval every 
    // time it fails seems a good start.
  });
}, 5*1000);
+2

edit: , ... , - .

I would suggest downloading a small js file that adds a class to an element of your page and then checks to see if this class is applied after the fact ... if you use jQuery

on a remote server loaded to your page after jQuery via a script tag

$('html').addClass('connected');

local code

if($('html').hasClass('connected')) {
    // connected
} else {
    // not connected
}
0
source

All Articles