PHP新手求助:扫码后表单提前提交,无法获取数据库数据
Hey there! I totally get why this is frustrating—barcode scanners are supposed to speed things up, not skip critical steps. Let's break down what's happening and fix it:
The Root Cause
Most barcode scanners automatically send an Enter key (carriage return) right after scanning a barcode. Since your form has a submit button, hitting Enter triggers an immediate form submission—before your code can pull product data from the database and populate the related fields.
Solution 1: Block Enter Key from Submitting the Form
We'll use JavaScript to listen for the Enter key in your product input field, stop it from submitting the form, and instead trigger your data-fetching logic.
First, update your product input to add a reusable class (for dynamic rows later) and adjust the existing attributes:
<input type="text" class="form-control product-input" name="product" id="rowNum0" autofocus />
Then add this JavaScript to your page (place it before the closing </body> tag or in a dedicated script file):
// Listen for Enter key in any product input (works for static + dynamic rows) document.getElementById('itemRows').addEventListener('keydown', function(e) { const inputField = e.target; // Check if the pressed key is Enter and it's a product input if (inputField.classList.contains('product-input') && e.key === 'Enter') { e.preventDefault(); // Stop the form from submitting early const rowNumber = inputField.id.replace('rowNum', ''); // Extract row number (0,1,2...) loadProductData(inputField.value, rowNumber); // Fetch and populate product data } }); // Function to fetch product data from your database function loadProductData(barcode, rowNumber) { // Call your PHP backend (replace with your actual endpoint) fetch(`get-product.php?barcode=${encodeURIComponent(barcode)}`) .then(response => response.json()) .then(data => { if (data.success) { // Populate fields for the current row document.getElementById(`p_name${rowNumber}`).value = data.productName; document.querySelector(`.price[data-row="${rowNumber}"]`).value = data.price; // Auto-focus to quantity field for faster input document.getElementById(`qtn${rowNumber}`).focus(); } else { alert("Product not found with this barcode!"); } }) .catch(error => { console.error("Error loading product data:", error); alert("Failed to load product information."); }); }
Solution 2: Backend PHP Script (get-product.php)
You'll need a simple PHP script to query your database and return product data as JSON:
<?php // Connect to your database (update with your credentials) $conn = new mysqli('localhost', 'db_username', 'db_password', 'your_database'); if (isset($_GET['barcode'])) { $barcode = $conn->real_escape_string($_GET['barcode']); $query = "SELECT product_name, price FROM products WHERE barcode = '$barcode'"; $result = $conn->query($query); if ($result->num_rows > 0) { $product = $result->fetch_assoc(); echo json_encode([ 'success' => true, 'productName' => $product['product_name'], 'price' => $product['price'] ]); } else { echo json_encode(['success' => false]); } } else { echo json_encode(['success' => false, 'message' => 'No barcode provided']); } $conn->close(); ?>
Notes for Dynamic Rows (Add Row Button)
When you add new rows with your addRow function, make sure:
- New product inputs have IDs like
rowNum1,rowNum2, etc., and theproduct-inputclass - Product name fields have IDs like
p_name1,p_name2 - Price fields include a
data-rowattribute matching the row number (e.g.,<input class="form-control price" data-row="1" ... />)
This ensures the JavaScript works seamlessly for all new rows you add.
Bonus: Disable Global Form Submission on Enter (Optional)
If you want to prevent Enter from submitting the form anywhere else in the form, add this:
document.querySelector('form').addEventListener('keydown', function(e) { if (e.key === 'Enter') { e.preventDefault(); } });
That should fix the auto-submit issue and let you load product data before submitting the form!
内容的提问来源于stack exchange,提问作者arslan sheikh

