jQuery(document).ready(function ($) {
// Hook into the form submission event
$('#form_edit-product-form').on('submit', function (e) {
e.preventDefault(); // Prevent form submission temporarily
// Get the SKU field value
var productSku = $('#field_sku2').val(); // Replace 'field_sku2' with your actual SKU field ID
if (!productSku) {
alert('Please enter a SKU.');
return false; // Stop submission
}
// Check if SKU is unique via AJAX
$.ajax({
url: ajaxurl, // WordPress AJAX endpoint
type: 'POST',
data: {
action: 'validate_unique_sku',
sku: productSku,
},
success: function (response) {
if (response.success) {
// SKU is unique, proceed with form submission
$('#form_edit-product-form').unbind('submit').submit(); // Re-enable and submit the form
} else {
// SKU is not unique, display an alert
alert('SKU "' + productSku + '" is already taken. Please use a unique SKU.');
}
},
error: function () {
alert('An error occurred while validating the SKU. Please try again.');
},
});
});
});