I am creating an Invoice System in PHP and MySQL. What I want is for the user to be able to select a product in a drop down field and the price of that product should be fetched from database and displayed in the price input field automatically using javascript. So far I am able to fetch the products and display them in a drop down field. Note that the name of the product and price are both stored in the same table.
<div class="col-md-4 mb-3">
<select name="product_name[]" id="live_search" class="form-control" placeholder="product name" required autocomplete="off">
<option value="" selected="selected"></option>
<?php
// fetch products
$sqlCAT="SELECT * FROM products";
$queryCAT=mysqli_query($dbCon, $sqlCAT);
while($result = mysqli_fetch_assoc($queryCAT))
{
$product = $result['product_name'];
$id = $result['product_id'];
?>
<option value="<?php echo $product ?>"><?php echo $product ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-2 mb-3">
<input type="number" name="product_price[]" id="search_result" class="form-control" placeholder="item price" required autocomplete="off">
</div>
3
Answers
I was able to solve the problem with the following code. I added an event listener function to the product drop down box and used ajax to fetch the price and append it to the price input field.
Secondly I created a file to fetch the prices
Lastly I added some javascript
The problem was solved
As you provided little in the way of code and virtually no database table details you will need to study and modify the following rather than take as a working example.
The essence of the following is:
SELECT
element(s) that will processchange
events. The event listener here tests that theselect
menu is named appropriately before sending a GET request using AJAX to the backend PHP server.ID
and anaction
in the querystring. By using theaction
parameter you could fire many AJAX requests to the same backend script but with different values foraction
if required.exit($price)
This is just one possible way of doing it…this could easily be modified to process ALL select elements and other elements too which would make it far more useful
You’re asking 2 things.
1.1 Add price to the option, since it’s in the same table you can do this easily (I guessed how your columns are named, so replace $productPrice & $productName with the correct values)
1.2 Fetch the selected option via Js & display in browser console for demo purposes
Update the snippet above to show the price to the price input box via the value property through JS