1

I make a GET request with ajax and expect a JSON value to be returned.

However, my hosting has a firewall installed. It only takes 2 requests per second, otherwise blocks the connection and shows an error page. (a blank page.) So if I make 3 requests in a second, third request never retrieve the JSON response. Hence, loading.gif keeps turning and turning.

How can I make a timeout in jQuery, let's say 5 seconds, so it'll callback the timeout function?

1
  • 1
    $.ajax accepts a timeout option. You can then test in the error handler what the cause for the error was (e.g. the timeout). Please have a look at the documentation: api.jquery.com/jQuery.ajax. Commented Feb 26, 2013 at 2:24

2 Answers 2

1

Try this:

$.ajax({
    url: YourUrl,
    async: true,
    timeout: 5000,       //5 seconds
    success: function(args) { 

                     // on success code
    }
})
Sign up to request clarification or add additional context in comments.

Comments

0

You can create your custom GET request with timeout function as a parameter:

$.getWithTimeOut = function(url, params, datatype, onsuccessfunction, aftertimeoutfunction, timeout){
     $.get(url, params, function(data) {
          onsuccessfunction(data);
          setTimeout(aftertimeoutfunction, timeout);
     }, datatype);
};

Then you just call:

$.getWithTimeOut('url/url', { param1: value1 }, 'json', function(data){
     //success code here
}, function(/*params*/){
   //timeout code here
}, 5000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.