fatihcan8
fatihcan8

Reputation: 49

Ajax returns [object Object] output

I have a cartItem variable which includes title, price etc. I make an AJAX request when I click the 'add to cart' button but it returns [object Object] output instead of its title and price.

let cartTitle = $('.card-title', addCartItem);
let cartDescription = $('.card-description', addCartItem);
let cartPrice = $('.price', addCartItem);

var id = this.dataset.productId

$.ajax({
  type: 'GET',
  url: ('/getData'),
  data: {
    id: id
  },
  success: function(data) {
    cartTitle.text(data.title)
    cartPrice.text(data.price)
    cartDescription.text(data.description)
    $('tbody').prepend(cartItem)
  }
})

Upvotes: 1

Views: 40

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337627

cartItem is an object. You need to create a string from it's properties to prepend() to the tbody.

In addition you need to append <tr> elements to the tbody, so the title and price values will need to be wrapped within that to ensure the HTML you create is valid. Try this:

success: function(data) {
  cartTitle.text(data.title)
  cartPrice.text(data.price)
  cartDescription.text(data.description)

  $('tbody').prepend(`<tr><td>${cartItem.title}</td><td>${cartItem.price}</td></tr>`);
}

Upvotes: 1

Related Questions