سؤال

I have a function which returns results (or not). The problem is when it does not return any value I get in the console the message

cannot read property 'done' of undefined

Which is true and I do understand the problem. Also, this error doesn't make my code stop working, but I would like to know if there's any chance of avoiding this?

The function in ajax is:

function getDelivery(){
    var items = new Array();

    $("#tab-delivery tr").each(function(){
        items.push({"id" : $(this).find('.form-control').attr('id'), "id_option" : $(this).find('.form-control').val()});
    });

    if(items.length > 0){
        return $.ajax({
            url: 'response.php?type=getDelivery',
            type: 'POST',
            data: {content: items}
        });
    }
}

And to call it I use:

getDelivery().done(function(data){ // the problem is here
    if(data == false){
        return;
    }
});

So, is there any way of avoid the error? I have tried without success the following:

if(items.length > 0){
    return $.ajax({
        url: 'response.php?type=getDelivery',
        type: 'POST',
        data: {content: items}
    });
}else{
    return false;
}

And I get the error:

Uncaught TypeError: undefined is not a function

هل كانت مفيدة؟

المحلول

You could just return a deferred, that way the done() callback won't generate errors, and you can choose to resolve it or not

if(items.length > 0){
    return $.ajax({
        url: 'response.php?type=getDelivery',
        type: 'POST',
        data: {content: items}
    });
}else{
    var def = new $.Deferred();
    def.resolve(false);
    return def;
}

FIDDLE

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top