Reputation: 543
I am trying to get the value/s of a property called quantity that is contained in a JSON array called items but I keep on getting "Uncaught TypeError: Cannot read property 'length' of undefined" at the start of the jQuery.each() loop. Could someone please explain where I am going wrong. Many thanks in advance!
JSON -
{"items":[
{"id":"12345", "quantity":"2",},
{"id":"54321", "quantity":"3",}
]}
AJAX -
$(":input").bind('keyup mouseup', function () {
var self = this;
$.ajax({
url: "https://example.com/cart/change.json",
dataType: "jsonp",
data: {
id: $(this).attr('id'),
quantity : $(this).val()
},
//JSON response
success: function(data) {
console.log(data); //formatted JSON data
$('#subtotal').html(data.items_subtotal_price); //set subtotal from JSON
console.log($(self).attr('id')); //item id of clicked input
$.each(data.items.quantity, function(key,val){
console.log(key + '-' + val)
}
)}
});
});
Upvotes: 0
Views: 1198
Reputation: 750
You are wrong in here.
$.each(data.items.quantity, function(key,val){
console.log(key + '-' + val)
});
Above code you are trying to point data.items.quantity which mean data.items is a Array not Object. Access the quantity inside each.
it should be like this
$.each(data.items, function(index, item){
console.log(item.quantity);
});
Upvotes: 3