You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP+Ajax商品名联动单价后切换商品名单价不更新的解决方案

Fix: Unit Price Doesn't Update After Manual Edit When Switching Item Names

Hey there, I see exactly what's going on here. When you manually edit the Unit Price textarea and then switch to a different Item Name, the price stays stuck on your last manual input instead of updating to the new item's price. Let's fix this!

Why This Happens

You're using innerHTML to set the textarea's content, but here's the key detail: textarea elements store their actual user-editable value in the value attribute, not in their inner HTML. Once you manually type something in, the innerHTML value gets out of sync with the real value—so your AJAX response is trying to update the wrong property entirely.

The Quick Fix

Update your JavaScript function to set the value property directly instead of innerHTML. This will force the textarea to overwrite any manual input with the new price from your database:

function fetch_select(val) {
  $.ajax({
    type: 'post',
    url: 'fetch_data.php',
    data: { get_option: val },
    success: function(response) {
      // Trim removes extra whitespace from the AJAX response
      document.getElementById("UnitPrice").value = response.trim();
    }
  });
}

Bonus Optimizations

Let's make this code more robust and secure while we're at it:

  1. Handle Missing Prices
    If there's no matching price for an item (or your AJAX returns empty), add a fallback to avoid a blank textarea:

    success: function(response) {
      const cleanPrice = response.trim();
      document.getElementById("UnitPrice").value = cleanPrice || "No price found";
    }
    
  2. Clean Up Invalid HTML
    Your select and textarea tags have duplicate class attributes (you wrote class="form-control" twice). Browsers ignore duplicates, so let's fix that—plus, the select2 class doesn't make sense on a textarea:

    <!-- Fixed Select Tag -->
    <select class="form-control select2" onchange="fetch_select(this.value);">
      <option selected="selected">Select a Category</option>
      <?php 
      $select = mysqli_query($con, "select ItemName from bincard group by ItemName"); 
      while ($row = $select->fetch_assoc()){
        echo "<option value='".$row['ItemName']."'>".$row['ItemName']."</option>";
      } 
      ?>
    </select>
    
    <!-- Fixed Textarea Tag -->
    <textarea 
      rows="1" 
      cols="1" 
      style="resize: none;" 
      class="form-control" 
      id="UnitPrice" 
      name="UnitPrice"
    ></textarea>
    
  3. Fix SQL Injection Risk
    Your current PHP code directly inserts user input into a SQL query, which is a critical security vulnerability. Use prepared statements to protect your database:

    <?php
    include ("common/DBCon.php");
    if (isset($_POST['get_option'])) {
      $itemName = $_POST['get_option'];
      // Prepare the query to prevent SQL injection
      $stmt = $con->prepare("SELECT SellingPrice FROM bincard WHERE ItemName = ?");
      $stmt->bind_param("s", $itemName); // "s" indicates we're passing a string value
      $stmt->execute();
      $result = $stmt->get_result();
      
      if ($row = $result->fetch_assoc()) {
        echo $row['SellingPrice'];
      } else {
        echo ""; // Or return your fallback message here
      }
      
      $stmt->close();
      exit;
    }
    ?>
    

With these changes, switching Item Names will always overwrite the Unit Price with the correct value—even after you've manually edited it.

内容的提问来源于stack exchange,提问作者Cashvilly Ace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:10:40