22

I am using jQuery getJSON() function. This function getting data with no problem. But sometimes waiting, waiting waiting... And my loading bar showing loading loading loadin at center of page. So jQuery ajax() function have an timeout variable. But i want to use getJSON function. And i think that i can use ajaxStart() and ajaxStop() functions. But how?

$('.loadingDiv')
    .hide()
    .ajaxStart(function() {
        $(this).fadeIn();
        setTimeout("throw '';",15000) //i used this but didn't work
        setTimeout("return;",15000) //i used this but didn't work
        setTimeout("abort();",15000) //i used this but didn't work.(Abort all ajax events)
    })
    .ajaxStop(function() {
        $(this).fadeOut();
    });
Pranjal Bikash Das
  • 1,092
  • 9
  • 27
pheaselegen
  • 398
  • 1
  • 4
  • 15
  • When you pass strings to `setTimeout` (which you should *never* do), it `eval`s them in the global scope. So, you can't `return` from it. – gen_Eric Jan 09 '13 at 15:28
  • You should set a timeout in your invocation of `.ajax` – Asad Saeeduddin Jan 09 '13 at 15:29
  • @Asad: The OP says he wants to use `$.getJSON` instead of `$.ajax`. – gen_Eric Jan 09 '13 at 15:29
  • What's wrong with using the more explicit `$.ajax` function? It maybe more lines of code, but it'll stop you from making problems like this. – gen_Eric Jan 09 '13 at 15:31
  • @RocketHazmat: `$.getJSON` is just a wrapper for `$.ajax`. See the manual: http://api.jquery.com/jQuery.getJSON/ – lethal-guitar Jan 09 '13 at 15:31
  • @lethal-guitar: I know that. I was just re-iterating was was said in the question. – gen_Eric Jan 09 '13 at 15:31
  • @Rocket Hazmat Perhaps the OP didn't realize that `.getJSON` is the same thing as calling `.ajax`. In anycase, the `.getJSON` call does not allow for the use of the `timeout` parameter – renab Jan 09 '13 at 15:39

6 Answers6

17

getJSON() is just a shorthand for the following:

$.ajax({
    dataType: "json",
    url: url,
    data: data,
    success: success
});

So you could use $.ajax() and specify the timeout option as desired. See also: http://api.jquery.com/jQuery.getJSON/

lethal-guitar
  • 4,438
  • 1
  • 20
  • 40
  • +1 exactly what I was thinking (hence the similarity in our answers, you were quicker on the draw though) – renab Jan 09 '13 at 15:37
  • There is a similar [answer here](http://stackoverflow.com/a/7613888/386579) that can be extended to add timeout for jquery ajax call. – shasi kanth May 06 '14 at 07:19
17

getJSON() returns a promise on which you can call the abort function :

var p = $.getJSON(..., function(){ alert('success');});
setTimeout(function(){ p.abort(); }, 2000);

EDIT : but if your goal is just to abort if it takes too much time, then lethal-guitar's answer is better.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    +1 because it allows the OP to use `.getJSON` rather than `.ajax` – renab Jan 09 '13 at 15:40
  • Yes true answer is 'use Ajax'. But i wrote in my question too. Anyway this answer was helpful. Thanks. – pheaselegen Jan 09 '13 at 15:41
  • but it won't help the issue or would it? the time that is taken for the `getJSON` is dues to wait for the server side script to complete and if that is taking time then aborting the request and then sending another won't help the issue – Muhammad Omer Aslam Nov 27 '17 at 20:57
12

As lethal-guitar mentioned getJSON() function is just an shorthand for $.ajax(). If you want to detect if a timeout has occurred rather than an actual error use the code below.

var request = $.ajax({
    dataType: "json",
    url: url,
    data: data,
    success: function( ) { },
    timeout: 2000
}).fail( function( xhr, status ) {
    if( status == "timeout" ) {
        // do stuff in case of timeout
    }
});
Bruno
  • 5,772
  • 1
  • 26
  • 43
3

There's always the nuclear route as well:

//Set AJAX timeout to 10 seconds
$.ajaxSetup({
  timeout: 10*1000
});

This will set all the AJAX requests your program makes (even via $.getJSON) to have a time out of 10 seconds (or what have you).

Richard
  • 56,349
  • 34
  • 180
  • 251
  • I have tried this using 1) $.getJSON with a URL and 2) $.ajax with only 'url' and 'dataType' attributes. $.ajax respects the global timeout (set using a thread sleep filter on my local server), and $.getJSON does not. Seems like this may be a bug in $.getJSON. – Jasman Jan 08 '16 at 23:04
1

the setTimeout function executes a set of code after a specified number of milisecons in the global scope.

The getJSON function (per the jQuery documentation here http://api.jquery.com/jQuery.getJSON/) is shorthand for:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

so you would want to make your call like so:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success,
  timeout: 15000
});

$('.loadingDiv')
    .hide()
    .ajaxStart(function() {
        $(this).fadeIn();
    })
    .ajaxStop(function() {
        $(this).fadeOut();
    });
renab
  • 373
  • 2
  • 9
1

I don't think any of these answers are ideal. I know this is years late, but what you want to do is use the success/error callback options of the .ajax(); method when receiving a JSONP response.

Example of how I would structure this:

    // Call
    $.ajax({

      // URL you want to get
      url: 'http://example.com/json?callback=?',

      // Set a realistic time in milliseconds
      timeout: 3000,

      // Put in success callback function here, this example
      // shows you the data you got back from the call
      success: function(data) {
        console.log(data);
      },

      // Put in an error handling function, just an alert in this case
      error: function(badData) {
        alert('The call was unsuccessful');
      },

      type: 'POST'
    });
serraosays
  • 7,163
  • 3
  • 35
  • 60