skip to Main Content

I am using ajax for getting tabular format in my page. The problem is it was working, currently I encounter this problem

My code

$.each(res,function(index,row){ 
              
      console.log(row.bookable);
//{id: 2, slug: "dire_international_queen", organization_id: 1, roomtype_id: 5, no_bed: "2", …}

      console.log(row.bookable.slug); // it show what i expect (working), but **"Uncaught TypeError: Cannot read property 'slug' of null"**


}

Error

Uncaught TypeError: Cannot read property ‘slug’ of null

2

Answers


  1. you are using for each So I suppose you are getting array results in ajax response.
    check two things here.

    (row.bookable !=null) and (row.bookable.slug !=null)
    

    it usually happened because you are getting some value null for “bookable” property

    $.each(res,function(index,row){ 
        if(row.bookable!=null)
         {
          console.log(row.bookable);
         }
    //{id: 2, slug: "dire_international_queen", organization_id: 1, roomtype_id: 5, no_bed: "2", …}
          //check here
          if(row.bookable !=null && row.bookable.slug!=null)
          console.log(row.bookable.slug); 
    
    })
    
    Login or Signup to reply.
  2. You have an object lists of data in the res variable. You are getting the error because somewhere in the look your program unable to find the slug property.

    Use hasOwnProperty() to check if the property exists, then apply the related action.

    $.each(res,function(index,row){ 
        if ( row.bookable.hasOwnProperty('slug') ) {
            console.log(row.bookable.slug);
        }
    }
    

    Take a look to learn in the details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search