4

I'm trying to verify the user's internet connection before form submit, so that my JavaScript validation function can throw an alert and return false if no connection.

I've tried: navigator.onLine - doesn't work in FF (only looks at whether browser in 'offline mode')

AJAX request to my own site:

$.ajax({  
  type: "GET",  
  url: "internet_test.php",  
  async: false, //trying to force a response before continuing
  timeout:8000,
  success: function(ret_text) {
    if(ret_text == 'yes') {
      return true;
    } else {
      alert("No Connection 1");
      return false;
    }
  },
  error: function(x, t, m) {
    if(t==="timeout") {
      alert("No Connection 2");
      return false;
    } else {
      alert("No Connection 3");  //this is the one triggered
      return false;
    }
  }
});

I get the alert for the third type of error, but then the form submits anyway. I'm guessing that the error overrides the fact that I tried to specify a synchronous check, and the JavaScript validator finishes before the AJAX can return false.

Is there a good way around this? Better way to do it?

Thanks!

JSP64
  • 1,454
  • 1
  • 16
  • 26
  • 2
    If they didn't have an Internet connection, how would they be getting to your form in the first place? – j08691 Mar 08 '13 at 21:55
  • What are you receiving in `ret_text`? – emco Mar 08 '13 at 21:57
  • @j08691: It can cut out. I got a complaint from a user that he lost his data when his spotty internet was down as he tried to submit, and it seems like a reasonable concern for long forms – JSP64 Mar 08 '13 at 21:57
  • @EmCo: internet_test.php is just – JSP64 Mar 08 '13 at 21:59

1 Answers1

2

I would go this way:

  1. Change the "submit" to "button" (or link) - it will stop submitting form.
  2. On-click for this button make an AJAX call and if everything is OK, then make form.submit();

It's just a draft, everything can be made more user-friendly, more robust for no-js browsers etc.

Ejzy
  • 400
  • 4
  • 13