9

I have this code requesting some folder info from a mysql DB:

function gotoDir(pmcat_id, pcat_id){
    $('#slideshowContainer').html('<img class="loader" src="/javascript/ajax-loader.gif">');
    $.post("/publish/includes/content.includes/functions.slideshow.php", 
        {  updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id },
        function(data){
             $('#pageSlideshow').html(data.content);
        }, "json"
    );
}

Sometimes the post request times out because of bad internet connection. Is it possible to set a timeout check on $.post() ? Ex: if $.post() uses more then X ms, reload the request.

UPDATE: Looks like I found a solution:

function gotoDir(pmcat_id, pcat_id){
    $('#slideshowContainer').html('<img class="loader" src="/javascript/ajax-loader.gif">');
    $.ajax({
        type:"post",
        url:"/publish/includes/content.includes/functions.slideshow.php",
        data: { updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id },
        dataType: "json",
        success:function(data) {
            if (data == null){
            alert('ajax failed. reloading...');
            gotoDir(pmcat_id, pcat_id);
        } else {
            $('#pageSlideshow').html(data.content);
        }
        }        
    });
}

Is this a OK way to do this? :S

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
horgen
  • 2,183
  • 10
  • 30
  • 34
  • 1
    No it's not Okay, since if the data var equals null doesn't mean the request has timed out, which would cause in an infinite requests if functions.slideshow.php is actually returning null! – ifaour Nov 03 '10 at 10:45

2 Answers2

29

$.ajax has all the functions you need to accomplish what you are asking for:

function gotoDir(pmcat_id, pcat_id) {
    $('#slideshowContainer').html('<img class="loader" src="/javascript/ajax-loader.gif">');
    $.ajax({
        type: "POST",
        url: "/publish/includes/content.includes/functions.slideshow.php",
        data: { updateSlideshowDir: 1, pmcat_id: pmcat_id, pcat_id: pcat_id },
        dataType: "json",
        timeout: 500, // in milliseconds
        success: function(data) {
            // process data here
        },
        error: function(request, status, err) {
            if(status == "timeout") {
                gotoDir(pmcat_id, pcat_id);
            }
        }
    });
}

Please note that you don't need to set the timeout option unless you want to trigger the error method after a specific time you want to set.

ifaour
  • 38,035
  • 12
  • 72
  • 79
  • Note that this is also a good template for a longpolling client-side script if you put gotoDir() to the success too :) – jave.web Dec 31 '13 at 11:18
3

You should use $.ajax() and $.ajaxError(), then with "ajaxComplete" you can check if your request timedout, or succeded.

Source: jQuery API

Gowri
  • 1,832
  • 3
  • 29
  • 53
MatuDuke
  • 4,997
  • 1
  • 21
  • 26