KubiRoazhon
KubiRoazhon

Reputation: 1839

How to detect an empty element of a JSON response

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

Answers (4)

Rino Raj
Rino Raj

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

Jagdish Idhate
Jagdish Idhate

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

Pavan Teja
Pavan Teja

Reputation: 3202

use typeof operator

if(typeof data.name!='undefined')
{
    console.log(data.name)
}

Upvotes: 0

Ayaz Ali Shah
Ayaz Ali Shah

Reputation: 3531

Jquery give you length function for the task

if ( data.length != 0 ){
    console.log(data.name);
}

Upvotes: 0

Related Questions