vikmalhotra
vikmalhotra

Reputation: 10071

jquery ajax: how to implement timeout when internet is not connected

I am trying to make an ajax request and I want to find out if the internet is not connected. So, I was thinking that if the ajax request gives a timeout error, it can somehow be equated to no internet connection (I know that is not correct). Anyhow, here's my code:

$.ajax({
        url: 'http://example.net/getdata',
        dataType: 'json',
        data: 'product=all',
        timeout: 3000,
        success: function(data) {
            if (data.success == 'yes') {
              alert('I was successful');
            } else {
              alert('I failed');
            }
        },
        error: function(objRequest, errortype) {
            if (errortype == 'timeout') {
              alert('I timed out');
            }
        }
    });

I tried sending a request when the internet was not connected, and I thought I would receive a "timeout" error after 3 seconds (since I have set timeout to 3000). But I received a "parseerror". Why did that happen?

What is the correct way to implement something like no internet connection?

Upvotes: 2

Views: 3335

Answers (1)

Jeff
Jeff

Reputation: 4146

I'm not sure why you are getting a "parseerror" but please see this fiddle:

http://jsfiddle.net/pgWCg/

JSFiddle allows you to send a data param for a delay to test timeout, so I've set delay to 3 seconds and your timeout value to 2 seconds, and it does indeed alert the "I timed out" message.

You can modify both values to ensure that the delay is working as expected.

Upvotes: 3

Related Questions