我正在使用WordPress 5.0.
2带WooCommerce 3.5.3
我在checkoutpage上有两个选择下拉字段。我想从billing\\u region下拉列表中检索所选region\\u代码值,然后根据该值填充billing\\u province select下拉列表,但ajax请求不返回任何内容(400)
吼叫我的代码
HTML :
<div class="delivery-form-row">
<label for="billing_region">Region :</label>
<select id="billing_region" name="billing_region">
<option value="" selected="" disabled="">- Select your region -</option>
<option value="01">REGION I </option>
<option value="02">REGION II </option>
<option value="03">REGION III </option>
</select>
</div>
<div class="delivery-form-row">
<label for="billing_province">Province :</label>
<select id="billing_province" name="billing_province">
<option value="" selected="">- Select your region first -</option>
</select>
</div>
functions.php
add_action( \'wp_enqueue_scripts\', \'enqueue_js_script\', 30);
function enqueue_js_script() {
wp_enqueue_script( \'custom-js\', get_stylesheet_directory_uri() . \'/js/custom.js\', array(\'jquery\'), \'1.0.0\', true );
wp_localize_script( \'custom-js\', \'postdata\', array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action (\'wp_ajax_call_wc_get_phprpcb_data\', \'wc_get_phprpcb_data\') ;
add_action (\'wp_ajax_nopriv_call_wc_get_phprpcb_data\', \'wc_get_phprpcb_data\') ;
function wc_get_phprpcb_data() {
global $wpdb;
if(isset($_POST[\'regcode\'])) {
$stmt = $wpdb->query( $wpdb->prepare("SELECT * FROM skjdbt_sphilippine_provinces WHERE region_code = " . $_POST[\'regcode\'] . " ORDER BY province_description ASC") );
$stmt->execute();
$provinces = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo wp_send_json_success($provinces);
wp_die();
}
}
custom.js :
$("#billing_region").change(function(){
var $this = $(this),
regcode = $this.val(),
$billingProvince = $("#billing_province");
console.log(regcode)
$.ajax({
method: \'post\',
url: postdata.ajax_url,
dataType: \'JSON\',
data: {
action: \'wc_get_phprpcb_data\',
regcode: regcode,
},
success: function(provinces) {
$billingProvince
.empty()
.append(\'<option value="" selected="" disabled="">Please choose your province</option>\');
provinces = JSON.parse(provinces);
provinces.forEach(function(province){
$billingProvince.append(\'<option value="\' + province.province_code + \'">\' + province.province_description +\'</option>\');
});
},
});
});
省表截图:
任何帮助都将不胜感激
[EDIT] @Krzysiek Dróżdż]
谢谢你的帮助,伙计。下面是工作代码。
add_action (\'wp_ajax_wc_get_phprpcb_data\', \'wc_get_phprpcb_data\') ;
add_action (\'wp_ajax_nopriv_wc_get_phprpcb_data\', \'wc_get_phprpcb_data\') ;
function wc_get_phprpcb_data() {
global $wpdb;
if(isset($_POST[\'regcode\'])) {
$regcode = $_POST[\'regcode\'];
$sql = "SELECT * FROM {$wpdb->prefix}philippine_provinces WHERE region_code = " . $regcode . " ORDER BY province_description ASC";
$result = $wpdb->get_results($wpdb->prepare($sql, $regcode));
echo json_encode($result);
die();
exit;
}
}