jQuery Validation plugin with AJAX and PHP Superglobals strange behavior

I wrote a HTML form in a WordPress template and I want to validate it with jQuery Validation plugin but I have problem with AJAX validation, this is an extraction of what I wrote:

add_action( ‘wp_ajax_fiscal_code_duplicated’, ‘fiscal_code_duplicated’ );
add_action( ‘wp_ajax_nopriv_fiscal_code_duplicated’, ‘fiscal_code_duplicated’ );

public function fiscal_code_duplicated() {

if ( !isset( $_POST[‘_nonce’] ) || !wp_verify_nonce( $_POST[‘_nonce’], ‘ajax-nonce’ ) ) {
die( __( ‘Operazione non autorizzata!’, ‘molarisk’ ) );
}

$fiscal_code = filter_input( INPUT_POST, ‘fiscal_code’, FILTER_SANITIZE_STRING );

if ( MyClass::is_value_duplicated( ‘fiscal_code’, $fiscal_code ) ) {
$result = ‘false’;
} else {
$result = ‘true’;
}

echo $result;
wp_die();

}

class MyClass {
public static function is_value_duplicated( string $field_name, string $field_value ) : bool {
global $wpdb;

$table = $wpdb->prefix . ‘molarisk_users’;
if ( $field_name == ’email’ || $field_name == ‘fiscal_code’ ) {
$query = $wpdb->prepare( “SELECT COUNT(*) FROM `$table` WHERE `$field_name` = %s”, $field_value );
$count = $wpdb->get_var( $query );
if ( $count > 0 ) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}

and this is the JavaScript part:

var starting_form = $( ‘#starting_form’ );
starting_form.validate({
rules: {
‘user[fiscal_code]’: {
required: true,
fiscal_code_regex: true,
remote: {
url: my.ajaxurl,
type: ‘post’,
data: {
action: ‘fiscal_code_duplicated’,
_nonce: my.nonce,
}
}
},

in function fiscal_code_duplicated I can’t get values from PHP superglobals array (both $_POST and $_GET), what’s wrong?

Read more here:: jQuery Validation plugin with AJAX and PHP Superglobals strange behavior

Leave a Reply

Your email address will not be published. Required fields are marked *