user1755474
user1755474

Reputation:

Set timeout on AJAX without $.ajax()

I want to set timeout after 2 seconds loading data. I am new in ajax so please clarify through my code...because i have already see many (set time out on ajax) answer but every one do through $.ajax().

how I can do through .load() ? It is possible or not ?

My AJAX code 1:

// Start of our new ajax code
        if (!url) {
            url = jQuery('#product_addtocart_form').attr('action');
        }
        url = url.replace("checkout/cart","ajax/index"); // New Code
        var data = jQuery('#product_addtocart_form').serialize();
        data += '&isAjax=1';
        jQuery('#ajax_loader').show();
        try {
            jQuery.ajax( {
                url : url,
                dataType : 'json',
                type : 'post',
                data : data,
                success : function(data) {
                    jQuery('#ajax_loader').hide();
                    parent.setAjaxData(data,true);
                }
            });
            jQuery("#productOptions").modal('hide');
        } catch (e) {
            //alert(e);
        }
        // End of our new ajax code

2:

// AJAX product options modal
$('.optionsTrigger').on('click', function() {
    var target, url;
    target = $(this).attr('data-target');
    url = $(this).attr('href');
    $(target).load(url, function(){
        $(target).modal({
            show: true
        });
    });
});
$('#productOptions').on('hidden', function() {
    $('#productOptions').html('<img src="<?php echo $this->getSkinUrl("img/loading.gif"); ?>" id="optionsLoading" />');

    window.setTimeout("Tick()", 2000);

    function Tick()
     {

     }  
   });

Upvotes: 1

Views: 290

Answers (2)

Bergi
Bergi

Reputation: 664599

First, wrap your head around the fact that Ajax is asynchronous (like setTimeout) - the callbacks are called somewhen in the future.

How to timeout? You could use

var request = jQuery.ajax(…);
setTimeout(function() {
    request.abort();
}, 2000);
request.done(function callback(){ … });

But it's much simpler than that, jQuery already has a timeout parameter for it's ajax() option object.

However, this is not possible using load - here not the jqXHR object is returned, but the current jQuery DOM-selection. Either, you have to globally configure ajax, or you don't use load and build the method yourself - it's not that hard, see source

Upvotes: 1

j0nes
j0nes

Reputation: 8099

jQuery has the ajaxSetup() method available. You can set all options to the normal ajax() method there, including the timeout option. The settings set there should also be available when you call your AJAX request via load().

Upvotes: 2

Related Questions