Reputation: 1839
I'm getting a JSON response after an AJAX call. The response contains some elements like id, name, number, etc. The method return sometimes just the id and the number, in other cases the id, the name and the number. In the success part of the AJAX, JQuery method I'm testing if I'm getting the right keys . When a key like name dosen't exists I'm getting an error : Cannot read property 'name' of null
. It's clear that's i have a problem in my if condition.
$.ajax({
url: "edit_info",
type: 'POST',
data: {
'id': id
},
success: function(data) {
if (data.name) {
console.log(data.name);
}
});
So any alternative
Upvotes: 0
Views: 69
Reputation: 6264
typeof
allows the identifier to never have been declared before.
if (typeof data.name != "undefined" && data.name.trim().length) {
console.log(data.name);
}
Upvotes: 2
Reputation: 7742
As you are getting Cannot read property 'name' of null
, means your data
object is null
You can check for falsy value
if(data && data.name){
console.log(data.name);
}
Upvotes: 0
Reputation: 3202
use typeof operator
if(typeof data.name!='undefined')
{
console.log(data.name)
}
Upvotes: 0
Reputation: 3531
Jquery give you length function for the task
if ( data.length != 0 ){
console.log(data.name);
}
Upvotes: 0