I have the following pseudo structure.
[
{"product":
{
"id":"14",
"product_title":"My Awesome Product!",
"product_desc":"An awesome product.."
}
},
{"product":
{
"id":"15",
"product_title":"My MORE Awesome Product!",
"product_desc":"An AWESOMER product..."
}
}
]
I am iterating it like this:
$.post('Ajax.php',function(res){
res = res.pop();
$.each(res,function(product){
alert(product.product_title);
});
});
However, only the last product_title is being shown. It does not go thru all of them.
Is it my code, or my JSON structure? Thanks!
EDIT: reason for the .pop();: Reading jQuery JSON Structure - cant get it to work
If you want to iterate just don't pop...
$.post('Ajax.php',function(res){
$.each(res,function( index, value ){
alert( value.product.product_title );
});
});
Also, your JSON structure has some redundancy, it could be written as:
[
{
"id":"14",
"product_title":"My Awesome Product!",
"product_desc":"An awesome product.."
},
{
"id":"15",
"product_title":"My MORE Awesome Product!",
"product_desc":"An AWESOMER product..."
}
]
Which means an array of products. You always want your arrays to contain things of single type. If you wanted to return multiple things from the server, this would be more appropriate structure:
{
"products": [
{
"id":"14",
"product_title":"My Awesome Product!",
"product_desc":"An awesome product.."
},
{
"id":"15",
"product_title":"My MORE Awesome Product!",
"product_desc":"An AWESOMER product..."
}
],
"kittens": [
{
"id":"14",
"name":"kitty"
},
{
"id":"15",
"name": "kitty"
}
]
}
An array of products and an array of kittens, never an array of products AND kittens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With