1

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)
  }
})
0

1 Answer 1

1

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>`);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.