How do I make a connection alert?

1

Well I'm a beginner in ajax and wanted to know how I can do an Internet connection check, and display a message on the screen whether or not I have an active internet connection (I imagine this is possible with Ajax, but I still do not find anything satisfactory on the internet.)

Here are some examples of what I want to do:

Source:yahoo.com

Source: olx.com.br

Thanks in advance for any contribution! ...

    
asked by anonymous 03.02.2018 / 17:27

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: link

Does not work in Opera , in case you would have to make a request with Ajax for your own website, if the request fails,     

03.02.2018 / 17:33
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 this, an exception is thrown. Here's an example of how to use it:

$.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');
        }
    }
});
    
03.02.2018 / 17:43