基于Ajax实现下拉菜单选择联动更新价格文本字段
Hey there! Let's fix this Ajax price update issue step by step—you're already on the right track with setting up the event listener, we just need to adjust the logic to send the selected product and fetch its price.
First, let's spot the key issues in your current code:
- Your
load-product.phpis only reloading product options instead of looking up the price for the selected item. - The JavaScript loads that file but doesn't pass the selected product or use the response to update the price field.
- You have a duplicate ID (
priceTxt) on both the price input and quantity input—this will break DOM selection, so we'll fix that first.
1. Fix the Duplicate ID in HTML
Find the quantity input field and change its ID to something unique (like quantityTxt) to avoid conflicts:
<input type="number" maxlength="1" min="1" max="5" class="form-control" id="quantityTxt">
2. Update the JavaScript to Fetch and Display the Price
Replace your Javascript.js code with this:
$(document).ready(function() { $("#ItemListDropDown").change(function() { // Grab the selected product name from the dropdown const selectedProduct = $(this).val(); // Send an Ajax request to get the product's price $.ajax({ url: "get-product-price.php", // We'll create this file next method: "POST", data: { productName: selectedProduct }, dataType: "json", // Expect JSON-formatted response success: function(response) { // Update the disabled price input with the fetched value if (response.price) { $("#priceTxt").val(response.price); } else { $("#priceTxt").val(""); // Clear if no price is found } }, error: function() { alert("Oops! There was an error fetching the product price."); } }); }); // Optional: Trigger the change event on page load to show the first product's price $("#ItemListDropDown").trigger("change"); });
What this does:
- When the dropdown selection changes, it captures the selected product name.
- Sends that name to a backend file via POST request.
- Parses the JSON response and updates the price input field.
- Adds basic error handling to alert users if something goes wrong.
3. Create the get-product-price.php File (Replace Your Old load-product.php)
This file will handle the database query to get the price of the selected product, using prepared statements to prevent SQL injection (critical for security):
<?php include 'Connection.php'; // Only proceed if the product name was sent via POST if (isset($_POST['productName'])) { $productName = $_POST['productName']; // Use prepared statement to safely query the database $sql = "SELECT Price FROM products WHERE Product_Name = ? AND Availability = 1"; $stmt = mysqli_prepare($con, $sql); mysqli_stmt_bind_param($stmt, "s", $productName); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) { // Return the price as JSON echo json_encode(['price' => $row['Price']]); } else { // No matching product found echo json_encode(['price' => null]); } mysqli_stmt_close($stmt); } else { echo json_encode(['price' => null]); } mysqli_close($con); ?>
Key improvements:
- Uses prepared statements to avoid SQL injection attacks (never directly insert user input into SQL queries!).
- Only fetches the price for the selected product, not reloading all products.
- Returns data in JSON format, which is easy to parse and use in JavaScript.
Why This Works for Future Development
This setup follows a standard, reusable Ajax flow:
- Frontend sends user input to the backend.
- Backend processes the request safely.
- Backend returns structured data to the frontend.
- Frontend updates the UI with the received data.
You can use this exact pattern for your other planned Ajax features (like adding items to the cart or updating the invoice table)—it’s a solid foundation for dynamic interactions!
内容的提问来源于stack exchange,提问作者Snake

