20

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.

Ritesh Chandora
  • 8,382
  • 5
  • 21
  • 38
  • 1
    `alert()` the `textStatus` and `errorThrown` and see how they change for different failure types. You should be able to find out the appropriate codes. – Blender Jun 15 '12 at 04:44
  • Check out http://stackoverflow.com/questions/189430/javascript-how-to-detect-that-the-internet-connection-is-offline and http://stackoverflow.com/questions/1730692/jquery-ajax-how-to-detect-network-connection-error-when-making-ajax-call – gopi1410 Jun 15 '12 at 04:48
  • @Blender when network is disconnected then nothing change occur in any arguments and it does not go in error function.. – Ritesh Chandora Jun 15 '12 at 04:52
  • @gopi1410 I already mention in Question that I am not able to use time out option. and both upper question have solution in form of time out variable. – Ritesh Chandora Jun 15 '12 at 04:55
  • Have you checked the [$.ajaxError()](http://api.jquery.com/ajaxError/) ?? – gopi1410 Jun 15 '12 at 04:57
  • @gopi1410 Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. and bro in my case Ajax request is not completed. – Ritesh Chandora Jun 15 '12 at 05:12
  • I haven't looked too much into [Offline.js](https://github.com/HubSpot/offline), but it may have some useful related code. – But I'm Not A Wrapper Class Nov 09 '15 at 16:13

6 Answers6

6

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.

DariusVE
  • 132
  • 1
  • 10
3

If your server was not very crowded, probably you could use a timer to start detecting the connection regularly when you start transferring the data (by using another ajax calling, for instance each 5 seconds). now you can use timeout.

Btw, 1)timeout doesn't always means network error. sometimes server's down also causes "timeout"

2)if the driver is down on client device, xhr.status = 0, and no timeout

lucian
  • 527
  • 5
  • 15
2

I had a similar problem and solved it with a simpel try/catch and a re-try delay of (say) 2 seconds:

function myAjaxMethod()
{
  try 
  {
    $.ajax({ ... });
  } catch (err) 
  { 
    console.log(err.message); 
    setTimeout(function(){myAjaxMethod(),2000});
  }
}
Morten Madsen
  • 111
  • 2
  • 6
1

I faced a similar situation like yours and fixed it by having a network check for every 5 seconds and if network is disconnected i would abort the ajax request manually which will end the ajax request.

Here i get the ajax XmlHttpRequest in the beforeSend event of the Jquery ajax call and use that object to abort the ajax request in case of network failure.

var interval = null;
var xhr = null;

$.ajax({
     beforeSend: function(jqXHR, settings) {  
          xhr = jqXHR;  // To get the ajax XmlHttpRequest 
     },
     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
                },
      complete: function(data)
                {
                    alert('Complete');
                    //To clear the interval on Complete
                    clearInterval(interval);
                },
    });

interval = setInterval(function() {
    var isOnLine = navigator.onLine;
        if (isOnLine) {
            // online
        } else {
             xhr.abort();
        }
     }, 5000);
Uvaise
  • 309
  • 2
  • 7
0

Try adding timeout: while constructing your $.ajax({}).

Also make sure to set cache: false, helpful sometimes.

Refer to Jquery's ajax() : http://api.jquery.com/jQuery.ajax/#toptions

You will get much more information there!

My thought s on your problem[updated]

@RiteshChandora , I understand your concern here. How ever I can suggest you to do 2 things.

  1. As you have post data ranging from 200kb to 5mb, you might want to choose a maximum timeout. and trigger for the same. Yes, this might be problematic, but with the design you chosen, the only way to monitor the POST progress is to do this way. if not, see point 2.

  2. I went through the flow, you are asking the user to copy the response Json from FB to your url. there are some problems here,

  3. The json data has sensitive information about the user, and he is posting it on a url without SSL encryption.

  4. Why should you prompt the user to post the acquired data on to your server? it should be easier if you user sever side scripts. Also you should never post huge data from the client to the server in occasions like these, where you could retrieve the same form the FBserver->your sevrer on the server side.

My suggested solution : after the user is authenticated , retrieve his friends list on the server side. do whatever you want on the server side, and display the result on the users screen.

This way all the burden will be taken by your server, also there is no need for the user to do any nasty json posting on your url.

Btw, your app idea is cool.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Eswar Rajesh Pinapala
  • 4,841
  • 4
  • 32
  • 40
  • I already mention in Question that I am not able to use time out option. its is not possible to find out appropriate timeout. – Ritesh Chandora Jun 15 '12 at 05:10
  • Rajesh I already mention in Question that I am not able to use time out option. – Ritesh Chandora Jun 15 '12 at 05:29
  • Sorry, I missed your note about time out. can you try catching the errorThrown? Its "NOT FOUND" when the server is not found. Cant you trigger the errorThrown for NOT FOUND? here : http://jsfiddle.net/epinapala/y4cva/ – Eswar Rajesh Pinapala Jun 15 '12 at 05:31
  • @Rajesh Answer you suggest works only when server responds something.. But bro my question is if Ajax call canceled in middle of completion then how to detect that situation. I want to give a user a message and roll back to the previous situation. – Ritesh Chandora Jun 15 '12 at 22:19
  • Are you saying that, how to handle the situation when the call doesnt even raches the server? cancelled even before data is posted to the server? if this is the case, What makes the ajax call cancel in midway? even before it reaches the server? of you say network problems, Then you should still try to capture what errorThrown is returning in that case, did you try that?? – Eswar Rajesh Pinapala Jun 16 '12 at 09:10
  • also see this: might help : http://geekswithblogs.net/lorint/archive/2006/03/07/71625.aspx – Eswar Rajesh Pinapala Jun 16 '12 at 09:16
  • @Rajesh yes I tested error thrown its not working. I am saying that when You send 1MB data with ajax call and suppose only 50% data is submitted and then ajax call failed. then how to handle that situation.And I checked your suggested link it says same thing use TIME OUT option which I cant use. – Ritesh Chandora Jun 16 '12 at 13:05
  • @Ritesh .. Can you post the example code on jsfiddle.net? Besides server being unavailable, I rally want to know what makes an Ajax request halt before completion? What helps us quickly solve this problem is 1 - what is the REASON for Ajax request to stop after , suppose 50% data is posted?? – Eswar Rajesh Pinapala Jun 16 '12 at 18:46
  • @Rajesh I am creating facebook application in which user submit its data to my app. Its working fine on high bandwidth internet. but When I taste this application on slow internet connection I found that sometimes its does not displaying result and continuously running. After various taste I found that it is because slow internet connection server didn't receive full data so it wont reply back. link to my app.. it is hosted on my college server. [link]http://andromeda.nitc.ac.in/~ritesh/fbpending/ – Ritesh Chandora Jun 16 '12 at 22:55
  • @Rajesh I really want to do that thing on server side... but there is a problem.. I will be happy if you answer this question... [link](http://stackoverflow.com/questions/10392298/how-can-i-copy-the-content-of-popup-box-in-javascript-or-jquery) – Ritesh Chandora Jun 18 '12 at 10:42
  • @RiteshChandora : I see why you requested this. Unfortunately this is not a better approach to server side implementation as well. For a rough idea, here is what you need to do. example : php-facebook sdk, implement a simple FB app that logs in a user and extract what ever information you want. That way there is no need to get the friends list using JS and then post it to the serevr. Get the Freinds list ont he server itself and operate on it. – Eswar Rajesh Pinapala Jun 18 '12 at 17:30
  • This :http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/ is the right way of doing this. use that as an example, and you will learn alot and implement the same mechanism in your own FB app. I am sorry i gave you a PHP example, But you are free to use any sdk, Hope this helps you get a good idea about the right approach. – Eswar Rajesh Pinapala Jun 18 '12 at 17:31
  • @EswarRajeshPinapala, your answer deviates from the question and does not provide any solution. – Vipin Parakkat Jun 18 '12 at 23:29
  • @VipinNair : Please see the answer, I already pointed how to approach this problem by setting maximum timeout. Its only after that i started talking about server side implementation. You are late in the show, reading random comments and commenting! – Eswar Rajesh Pinapala Jun 18 '12 at 23:39
  • @EswarRajeshPinapala It is already mentioned in the question that timeout is not an acceptable solution and proposing it as an answer is not very wise. Server side implementation is also not a viable solution since the user wants to detect the connection failure in the client side. – Vipin Parakkat Jun 18 '12 at 23:44
  • @VipinNair :Did you know that the only way to detect a connection failure is to catch the timeout exception? If the user doesn't know it, you should make him aware of it(instead of not helping and randomly commenting on others who are trying to help) Or if you know a better way to detect the con failure, let us know. did you atleast look at the user's application? he is retrieving the response from FB->displaying it in a text field->prompting the user to copy and post it to his server, Do you really think server side impl is not viable? if you have a solution, HELP and dont mess! – Eswar Rajesh Pinapala Jun 18 '12 at 23:51
-5
   error: function(xhr, textStatus, thrownError)
                    {
                       alert(xhr.status);
                       alert(thrownError);
                       alert(textStatus);

                    }

Try them.. TextStatus (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, thrownError receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

If Internet disconnects,the response wont be received and maximum it would be a timeout message..

Kabilan S
  • 1,104
  • 4
  • 15
  • 31
  • Some references...http://api.jquery.com/jQuery.ajax/ and http://api.jquery.com/ajaxError/ – Kabilan S Jun 15 '12 at 05:14
  • 2
    Answer you suggest works only when server responds something.. But bro my question is if Ajax call canceled in middle of completion then how to detect that situation. I want to give a user a message and roll back to the previous situation. – Ritesh Chandora Jun 15 '12 at 05:28