Show PHP object data inside javascript

143 views Asked by At

I know there have been just too many questions so far asking about PHP and JS working together...I went through them, but I cannot find an elegant solution for my use case.

What I currently have is following PHP code in my webpage that fetches product info and shows it:

<?php
  $p= new Product($prodId);
  $p->getProductInfo();

  //now show product info...
  echo "<div>Product Name: ".$p['productName']."</div>";
  echo "<div>Product Rating: ".$p['productRating']."</div>";
  //etc...
?>

Now what I have been asked to do is instead of showing this data directly in the page, I should show it only when a button is clicked. And I should show it inside a bootbox modal dialog box

So I did:

<span id='prod-details'> View Product Details </span>
<input type='hidden' id ='prod-id' value='<?php echo $p['productId'];?>'>

And in my jquery file I have:

$('#prod-details').click(function(
   var prodId = $('#prod-id').val();
   productDetail = "Product Details for "+prodId;

   //how do I get rest of product details from PHP object?

   bootbox.alert(productDetail);
));

Any help is very much appreciated...I have been trying hard to make this work.

2

There are 2 answers

1
Robin Woudstra On

What I normally do is echo the information inside the bootbox modal div and just hide/show the bootbox modal div with an onClick function

0
Daniel Katzan On

you can either put it in your html file like this:

<script>
    var productName = <?php echo $p['productName'];?>;
</script>

or exactly like you did with the product id, just put all the data you need inside the input div (or any oher div releated to that product)

<input type='hidden' id ='prod-id' value='<?php echo $p['productId'];?>' productName='<?php echo $p['productName'];?>'>

and then using jquery get that data like you got the id

var prodName = $('#prod-id').attr('productName');