6

jQuery: How to enable timeout for $.ajax({dataType:'jsonp'...? Is there any solution? http://jsfiddle.net/laukstein/2wcpU/4

$.ajax({
    type:"GET",
    url:'http://lab.laukstein.com/ajax-seo/.json',
    dataType:'jsonp',
    timeout:200, // Not working with dataType:'jsonp'
    success:function(data){$('#content').html(data.content);},
    error:function(request,status,error){$('#content').html('request failed');}
});

I do not like to use some plugins for that, like http://code.google.com/p/jquery-jsonp.

Jens Roland
  • 27,450
  • 14
  • 82
  • 104
Binyamin
  • 7,493
  • 10
  • 60
  • 82
  • Duplicate: http://stackoverflow.com/questions/1002367/jquery-ajax-jsonp-ignores-a-timeout-and-doesnt-fire-the-error-event – Marcus Whybrow Jan 13 '11 at 12:20
  • 1
    I would not like to use some plugins for that, like http://code.google.com/p/jquery-jsonp/ – Binyamin Jan 13 '11 at 18:08
  • Maybe you could take a look at the plugins code and see what it does, however the answer I linked to states that it is a limitation of JSONP. – Marcus Whybrow Jan 13 '11 at 18:12

2 Answers2

4

Here is my solution with setTimeout and clearTimeout http://jsfiddle.net/laukstein/2wcpU/7/

$('#content').ajaxStart(function(){
    $(this).html('Loading...');
});
var timer=window.setTimeout(function(){
    $('#content').html('Loading seems to be taking a while. Try again.');
},2000);
$.ajax({
    type:"GET",
    url:'http://lab.laukstein.com/ajax-seo/.json',
    dataType:'jsonp',
    success:function(data){
        window.clearTimeout(timer);
        $('#content').html(data.content);
    },
    error:function(){
        window.clearTimeout(timer);
        $('#content').html('The request failed. Try to refresh page.');
    }
});
Binyamin
  • 7,493
  • 10
  • 60
  • 82
0

Binyamin,

this SO answer should help you:

jQuery ajax (jsonp) ignores a timeout and doesn't fire the error event

basically, suggests using jquery.jsonp instead of $ajax

Community
  • 1
  • 1
jim tollan
  • 22,305
  • 4
  • 49
  • 63
  • That's an exact duplicate of the question the same question linked to in my comment on the question. – Marcus Whybrow Jan 13 '11 at 12:24
  • sorry marcus, can see that now. comment wasn't there as i started my answer :) – jim tollan Jan 13 '11 at 12:26
  • 1
    I seen that answers already before. Unfortunately I would not like to use some plugins for that like http://code.google.com/p/jquery-jsonp/. So I'm looking for some other solution? – Binyamin Jan 13 '11 at 18:09
  • Not a problem, but it probably shouldn't be listed as an answer to the question, but as a comment. – Marcus Whybrow Jan 13 '11 at 18:14