https://gopangolin.com/beyond-admin-ajax-using-wordpress-rest-api/
<?php
add_action( 'wp_enqueue_scripts', 'rest_site_scripts', 999 );
function rest_site_scripts() {
// Enqueue our JS file
wp_enqueue_script( 'rest_appjs',
get_template_directory_uri() . '/js/app.js',
array( 'jquery' ), filemtime( get_template_directory() . '/js/app.js'), true
);
// Provide a global object to our JS file contaning our REST API endpoint, and API nonce
// Nonce must be 'wp_rest' !
wp_localize_script( 'rest_appjs', 'rest_object',
array(
'api_nonce' => wp_create_nonce( 'wp_rest' ),
'api_url' => site_url('/wp-json/rest/v1/')
)
);
}
/**/
add_action( 'rest_api_init', 'rest_validate_email_endpoint' );
function rest_validate_email_endpoint() {
// Declare our namespace
$namespace = 'rest/v1';
// Register the route
register_rest_route( $namespace, '/email/', array(
'methods' => 'POST',
'callback' => 'rest_validate_email_handler',
'args' => array(
'email' => array( 'required' => true ), // This is where we could do the validation callback
)
) );
}
// The callback handler for the endpoint
function rest_validate_email_handler( $request ) {
// We don't need to specifically check the nonce like with admin-ajax. It is handled by the API.
$params = $request->get_params();
// Check if email is valid
if ( is_email( $params['email']) ) {
return new WP_REST_Response( array('message' => 'Valid email.'), 200 );
}
// Previous check didn't pass, email is invalid.
return new WP_REST_Response( array('message' => 'Not a valid email.'), 200 );
}
?>
<script>
jQuery(document).ready(function($) {
$( '#form' ).on( 'submit', function(e) {
e.preventDefault();
// Get our email from the input
var email = $( '#email' ).val();
// Compile our data object - notice that it is only the email as opposed to the admin-ajax method.
// The nonce is sent in a request header - see beforeSend in $.ajax
// No action is required, we specify the direct endpoint we created above as the url in $.ajax
var data = {
email: email,
};
// Fire our ajax request!
$.ajax({
method: 'POST',
// Here we supply the endpoint url, as opposed to the action in the data object with the admin-ajax method
url: rest_object.api_url + 'email/',
data: data,
beforeSend: function ( xhr ) {
// Here we set a header 'X-WP-Nonce' with the nonce as opposed to the nonce in the data object with admin-ajax
xhr.setRequestHeader( 'X-WP-Nonce', rest_object.api_nonce );
},
success : function( response ) {
console.log(response);
$( '#result' ).html(response.message);
},
fail : function( response ) {
console.log(response);
$( '#result' ).html(response.message);
}
});
});
});
</script