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
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.
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.
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.
An undefined error is when we declare a variable in the code but do not assign a value to it before printing the variable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With