Jcode Jcode - 6 months ago 12
jQuery Question

PHP passing value via button best practice

Below is my code, basically it pulls information from the database and displays the stock associated, from here I have a details button which I want to use to send data to another html page to display more information on the product, add to cart etc.

My question is what is considered "Best practice" to send this information, should I simply make a form that gets the ID from the array and sends it on click? Or is there a more efficient way say using jquery?

I assume best practice would be to have a function which the value is passed to from the button form?

<section>
<div class="row">
<div class="col-md-12">
<div class="heading">
<h1>New Mag Wheel Arrivals</h1>
</div>
</div>
</div>
<div class="row products">
<?php while ($product = mysqli_fetch_assoc($wheelResult)) : ?>
<div class="col-md-3 col-sm-6">
<div class="product border">
<div class="image">
<a href="#"><img src=" <?= "images/wheels/wheelphotos/" . $product["bigpic"]; ?>"
alt="<?= $product["manufacturer"]; ?>" class="img-responsive img-demo"></a>
</div>
<div class="ribbon ribbon-quick-view sale">
<div class="theribbon">NEW</div>
<div class="ribbon-background"></div>
</div>
<div class="ribbon ribbon-quick-view logo">
<div class="theribbon"><img src="images/wheels/logos_small/Vs2.png"></div>
<div class="ribbon-background"></div>
</div>
<div class="text text-background">
<h4><a href="detail.php"><?= $product["diam"] . "\" " . $product['manufacturer'] ?></a></h4>
<p class="brand"><a href="#"><?= "Model " . $product["part_no"]; ?></a></p>

<button class="btn btn-default btn-sm btn-primary" href="detail.php">Details</button>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</section>


Sudo code form example

EG

<form action=details.php method="GET">
<button class="btn btn-default btn-sm btn-primary" href="detail.php">Details</button>
hidden-value = $product["recid"]
</form>

Answer

As you need to load an entirely new page, so Ajax isn't going to bring any big improvements in terms of user friendliness. I'd suggest you to do this simply like below:

On product listing page (in while loop), place your button like this:

<a href="detail.php?id=<?php echo $product["recid"];?>"><button class="btn btn-default btn-sm btn-primary" >Details</button></a>

On detail.php page, simply take the id from $_GET request and then fetch detail for the product from database:

i.e. "SELECT * FROM `products` WHERE `product_id` = ?"

Hint: Use $_GET['id'] for ? as it will contain id of product passed from previous page.

Comments