Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery Cannot read property 'done' of undefined - avoid this

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

like image 468
Linesofcode Avatar asked Apr 16 '14 17:04

Linesofcode


People also ask

How do you fix undefined property Cannot be read?

The “cannot read property of undefined” error occurs when you attempt to access a property or method of a variable that is undefined . You can fix it by adding an undefined check on the variable before accessing it.

What is Cannot read property of undefined?

The "Cannot read properties of undefined" error occurs when trying to access a property on an undefined value. You often get undefined values when: accessing a property that does not exist on an object. accessing an index that is not present in an array.

How do you fix TypeError Cannot read properties of null?

The "Cannot read property 'click' of null" error occurs when trying to call the click method on a null value. To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.

When can you have an error that says undefined value on the screen?

An undefined error is when we declare a variable in the code but do not assign a value to it before printing the variable.


1 Answers

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

like image 163
adeneo Avatar answered Sep 23 '22 09:09

adeneo