WordPress基于CSV的卡片价格计算器AJAX改造技术求助
Fixing AJAX-Powered Card Price Calculator in WordPress
Let's break down the issues in your current code and walk through the corrected implementation step by step—no more confusion, just clear, working logic.
Key Issues in Your Current Code
- Undefined
$rowsin AJAX Function: Yourget_price()tries to use$rows, but this variable only exists in your form's PHP context. AJAX requests run independently, so you need to re-read the CSV directly in the AJAX handler. - Broken
wp_localize_script: You used the wrong script handle (custom_script-scriptinstead ofcustom_script) and missed closing the array bracket, which breaks the AJAX URL variable. - Incorrect AJAX Response: Returning a value from
get_price()won't send data to the frontend—you need to output the result and terminate the script (WordPress has helper functions for this). - JS URL Typo: You referenced
ajax_object.ajax_url, but your localized variable is namedajaxurl. - No User-Facing Result: Your JS only logs to the console; users need a visible place to see the price.
Step 1: Correct PHP Script Enqueuing & AJAX Handler
First, fix your script loading and AJAX logic. Replace the placeholder CSV path with your actual file path.
// Enqueue AJAX script and localize variables add_action('wp_enqueue_scripts', 'enqueue_custom_ajax_script'); function enqueue_custom_ajax_script() { wp_enqueue_script( 'custom_script', plugin_dir_url( __FILE__ ) . 'js/custom.js', array('jquery'), '1.0', true // Load in footer for better performance ); wp_localize_script( 'custom_script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } // AJAX handler for logged-in and guest users add_action('wp_ajax_get_price', 'get_price'); add_action('wp_ajax_nopriv_get_price', 'get_price'); function get_price() { // Validate incoming data if (!isset($_POST['card']) || !isset($_POST['quantity'])) { wp_send_json_error('Missing required selections'); } $card = intval($_POST['card']); $quantity = intval($_POST['quantity']); // Update this to your actual CSV file path $standard_csv = plugin_dir_path( __FILE__ ) . 'pricing.csv'; // Check if CSV exists if (!file_exists($standard_csv)) { wp_send_json_error('Pricing data not found'); } // Read and parse CSV $header_row = fgetcsv(fopen($standard_csv, "r")); $rows = array_map('str_getcsv', file($standard_csv)); unset($rows[0]); // Remove header row // Validate selections exist in CSV data if (!isset($rows[$quantity]) || !isset($rows[$quantity][$card])) { wp_send_json_error('Invalid card or quantity selection'); } // Send success response $price = 'Price: £' . $rows[$quantity][$card]; wp_send_json_success($price); // Always terminate AJAX requests wp_die(); }
Step 2: Updated Form Code
Add a container to display the price, and clean up form output with security sanitization:
<?php // Read CSV for form dropdown options $standard_csv = plugin_dir_path( __FILE__ ) . 'pricing.csv'; $ch = fopen($standard_csv, "r"); $header_row = fgetcsv($ch); $rows = array_map('str_getcsv', file($standard_csv)); unset( $rows[0] ); ?> <!-- The Calculator Form --> <form action="" method="post" name="calc" id="calc"> <div> <label for="card">Card Type:</label> <select name="card" id="card" required> <option value="">Please Select</option> <?php unset( $header_row[0] ); foreach ( $header_row as $key => $card ){ echo '<option value="' . esc_attr($key) . '">' . esc_html($card) . '</option>'; } ?> </select> </div> <div style="margin: 10px 0;"> <label for="quantity">Quantity:</label> <select name="quantity" id="quantity" required> <option value="">Please Select</option> <?php foreach ( $rows as $key => $row ){ echo '<option value="' . esc_attr($key) . '">' . esc_html($row[0]) . '</option>'; } ?> </select> </div> <button type="submit" name="get-price">Get Price!</button> </form> <!-- Container to display the price result --> <div id="price-result" style="margin-top: 15px; padding: 10px; border: 1px solid #eee;"></div>
Step 3: Corrected JavaScript (custom.js)
Fix the URL typo, add validation, and display results to users:
jQuery(document).ready(function($) { $('#calc').submit(function(event) { event.preventDefault(); var card = $('#card').val(); var quantity = $('#quantity').val(); var resultContainer = $('#price-result'); // Basic frontend validation if (!card || !quantity) { resultContainer.html('<p style="color: #dc3232;">Please select both card type and quantity</p>'); return; } // Send AJAX request $.ajax({ type: 'POST', url: ajax_object.ajaxurl, data: { action: 'get_price', card: card, quantity: quantity }, beforeSend: function() { // Show loading state resultContainer.html('<p>Calculating...</p>'); }, success: function(response) { if (response.success) { resultContainer.html('<p style="color: #46b450;">' + response.data + '</p>'); } else { resultContainer.html('<p style="color: #dc3232;">Error: ' + response.data + '</p>'); } }, error: function(jqXHR, textStatus, errorThrown) { resultContainer.html('<p style="color: #dc3232;">Something went wrong: ' + errorThrown + '</p>'); console.log('AJAX Error:', textStatus, errorThrown); } }); }); });
Additional Notes
- Security: We added
intval()to sanitize incoming values andesc_attr()/esc_html()for form output to prevent XSS vulnerabilities. - Error Handling: The AJAX function checks for missing data, invalid file paths, and bad selections, returning clear errors to users.
- UX: A loading state lets users know the request is in progress, instead of wondering if the button did anything.
内容的提问来源于stack exchange,提问作者Brian Revie
相关产品推荐
相关产品推荐

