J'ai cette fonction pour récupérer les codes postaux de WooCommerce
public function validate_zipcode () {
global $wpdb, $woocommerce;
$sql = ' SELECT location_code FROM ' . $wpdb->prefix. 'woocommerce_shipping_zone_locations ';
$sql .= "WHERE location_code IS NOT NULL";
$zones = $wpdb->get_results($sql);
return $zones;
}
add_action( 'wp_ajax_nopriv_validate_zipcode', array( &$this, 'validate_zipcode' ));
Je voudrais utiliser Jquery pour obtenir les résultats, mais je ne peux pas, la réponse d'erreur est une mauvaise demande, qu'est-ce que je fais mal?
jQuery(".check-Zip").click(function(){
var zipCode = jQuery("#custom_Zip").val();
var zipArray = [];
jQuery.ajax({
type: 'GET',
url: ajaxurl,
data: {
action: 'validate_zipcode'
},
success: function(data) {
console.log( data );
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log( jqXHR, textStatus, errorThrown );
}
});
J'ai pu résoudre ce problème en utilisant l'API WooCommerce avec uniquement jQuery.
$(".check-Zip").on('click', function () {
var zipCode = jQuery("#custom_Zip").val();
var zipArray = [];
var url = WPURLS.template_url;
$(".Zip-msg").remove();
$.ajax({
type: 'GET',
url: url + '/wp-json/wc/v2/shipping/zones/1/locations',
dataType: "json",
data: {
type: 'postcode'
},
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
},
success: function (data) {
$.each(data, function (key, value) {
zipArray.Push(value.code);
}); //end each function
if ($.inArray(zipCode, zipArray) > -1) {
$("#custom_Zip_checkout_field").append("<div class='Zip-msg'>Service is available at " + zipCode + "</div>");
} else {
$("#custom_Zip_checkout_field").append("<div class='Zip-msg'>Oops! We are not currently servicing your area.</div>");
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
}); //end ajax function
});
if($.inArray(zipCode, zipArray) > -1 ) {
jQuery("#custom_Zip_checkout_field").append("<div class='Zip-msg'>Service is available at " + zipCode + "</div>");
}else{
jQuery("#custom_Zip_checkout_field").append("<div class='Zip-msg'>Oops! We are not currently servicing your area.</div>");
}
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log( jqXHR, textStatus, errorThrown );
}
});//end ajax function
});