I have the following PHP Code that outputs the query result (which is simply a mapping of a Product Name and its corresponding unit price) to a JSON file. The PHP code also populates the drop down list.
I have no problem in creating the JSON file and populating the drop down list. My main concern is this:
When the user selects a Product Name from the drop down list, how do I auto-populate another text field to display the Product's corresponding unit price?
<label for="p_name">Product Name</label>
<div class="input-group">
<div class="input-group-btn">
<input type="text" class="form-control" name="p_name" id="p_name" style="width: 300px;" required>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span></button>
<ul class="dropdown-menu" role="menu" style="width: 300px;">
<?php
$connstring = pg_connect("host=localhost dbname=myDB user=postgres password=password")
or die('Could not connect: ' . pg_last_error());
$select = "SELECT p_name, unit_price FROM Product";
$executeSelect = pg_query($select) or die('Postgresql: ' . pg_last_error());
$result = array();
while ($line = pg_fetch_array($executeSelect, null, PGSQL_ASSOC)) {
$index = 0;
foreach ($line as $col_value) {
if ($index % 2 == 0)
{
//Display Product Name in the drop down list
echo "<li><a>$col_value</a></li>";
$index++;
}
else
{
$index++;
}
}
//Store query output to the result array
$result[] = $line;
}
//Save the query output to a JSON file
file_put_contents('C:\Apache\htdocs\productList.json', json_encode($result), LOCK_EX);
pg_free_result($executeSelect);
pg_close($connstring);
?>
</ul>
</div><!-- /btn-group -->
</div><!-- /input-group -->
<label for="unit_price">Unit Price</label>
<input type="number" class="form-control" name="unit_price" id="unit_price"></input>
Use Javascript to show the product's corresponding unit price.
JQuery for loading the JSON file on the server.
$.getJSON('products.json', function(data) {
// process the data
});
For more information on $.getJSON()
, check out this link
Tip : Better load the entire JSON file once in the onReady() event of the document and populate the Product name dropdown box. Using PHP is not a good choice of design by my experience.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.