How to detect Ajax call failure due to network disconnected
ajax, javascript, jquery
Solution
Try this:
First create a "ping" ajax call with setInterval every 5 seconds
function server_ping()
{
$.ajax({
url:"url to ping",
type: "POST"
});
}
var validateSession = setInterval(server_ping, 5000);
then arm your .ajaxError trap:
$(document).ajaxError(function( event, request, settings ) {
//When XHR Status code is 0 there is no connection with the server
if (request.status == 0){
alert("Communication with the server is lost!");
}
});
Remember Ajax calls are Asynchronous by default, so when the pings are going to the server and the request cannot reach the server the value on the XHR status is 0, and the .ajaxError will fire and you must catch the error and handle the way you want it.
Then you can send your data to the server, if the connection is lost when sending the data you get the error reported by the ping.
Problem
I am sending lots of data using jquery ajax method to web sever and client side respond only after receiving acknowledgment from server, now suppose network connection lost in MIDDLE of ajax call then how to detect this situation. ``` $.ajax({ url:'server.php', data:'lots of data from 200KB to 5MB', type:'post', success: function(data) { alert('Success'); //some stuff on success }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Failure'); //some stuff on failure } }); ``` This is my code and and it does not give error in middle of ajax call if get internet is disconnected. NOTE : I cant use time out because data size is vary from 200kb to 5MB and server response time calculation is not feasible.