How to make connection alert?

Asked

Viewed 41 times

1

good i am beginner in ajax and wanted to know how I can do a check of connection to the internet, and display message on the screen whether or not you have an active connection to the internet (I imagine this is possible with Ajax, but still not found anything satisfactory on the internet).

Below are some examples of what I want to do:

alerta de conexão yahoo

Source: yahoo.com

alerla de conexao olx Source: olx.com.br

Thanks in advance for any contribution!...

2 answers

2


When you click the button you can do this

if (navigator.onLine) {
  console.log('online'); //mas voce coloca seu algoritmo
} else {
  console.log('offline');
}

source: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine

Does not work in opera, in case you would have to make a request with Ajax to your site, if the request fails, the chances that there is no internet are great.

  • Paid'mare bro!... Really good, and simple!

  • Thanks for the help, it worked right here!... (The question of the opera not being compatible I believe it will not bring big problems)

1

If you want to test the connection in general you can use navigator.onLine. Already if you want to put a timeout on your AJAX calls you can use the parameter timeout (if using Jquary) that accepts a number that is the time in milliseconds that the function should expect a return. After that, an exception is thrown. Here’s an example of how to use:

$.ajax({
    url: 'script.php',
    method: 'post',
    dataType:"json",
    timeout: 60000,
    error: function(jqXHR, exception){
        if(exception == 'timeout'){
            alert('Tempo limite de 6 segundos foi ultrapassado');
        }
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.