I have a php loop that loops through products and their data:
<?php foreach ($this->products as $product) { ?>
<script type=text/javascript>
product = {
id: $product->virtuemart_product_id,
name: $product->product_name
};
</script>
<?php } ?>
The data contains information about the product un the $product like so:
Is it possible to add the data to a existing javascript array or object in each of the loops? Basically it will add the data of the loop to the javascript array or product.
Any help would be appreciated :)
There is a more better and clean way, use json_encode
PHP
<?php
$data = array();
foreach( $this->products as $product ) {
$data[] = array(
"id" => $product->virtuemart_product_id,
"name" => $product->product_name
);
}
?>
HTML
<script type=text/javascript>
var product = <?php echo json_encode( $data ) ?>;
</script>
You can also use
var product = <?php echo json_encode( $product ) ?>;
So when you want to access the product with javascript, your code will be
<script type="text/javascript">
for( i in product ) {
console.log( product[i] );
}
</script>
You can use json using the php function json_encode:
<script type='text/javascript'>
<?php
$products = $this->products;
$js_array = json_encode($products);
echo "var products = ". $js_array . ";\n";
?>
</script>
Another way to do the same thing:
<script type="text/javascript">
var products= <?php echo json_encode($products); ?>;
for(var i=0;i<n;i++)
{
alert(products[i]);
}
</script>
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