I'm trying to perform an action with AJAX in a Child theme template in Wordpress. I've looked into many similar issues. However, I couldn't find a solution. I've been dealing with this for about 2 hours. I'll be glad if anyone can help.
I have checked the error.log file several times. However, there is no problem.I am getting the following error in the browser console:
XHRPOSThttps://example.com/wp-admin/admin-ajax.php [HTTP/3 400 Bad Request 905ms]
...themes/child-theme/process/template.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button type="button" id="continue_process" onclick="continue_process()">Continue</button>
<script>
function continue_process() {
var ajax_nonce = '<?php echo wp_create_nonce( "before_process_nonce" ); ?>';
var ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>';
jQuery.ajax({
url : ajax_url, /* WordPress AJAX endpoint.*/
method : 'post',
data : {
'action' :'x_before_process',
'security' :ajax_nonce
},
success : function( response ) {
/* Get AJAX data from */
const obj = JSON.parse(response);
console.log(obj.message);
},
error : function( err ) {
/*Error */
console.log(err)
}
});
}
</script>
</body>
</html>
...themes/child-theme/process/process-ajax.php
<?php
if ( ! defined( 'ABSPATH' ) ){exit; /*Exit if accessed directly*/ }
add_action("wp_ajax_nopriv_x_before_process", "x_before_process");
function x_before_process() {
if(!wp_verify_nonce( sanitize_key($_POST['security']), 'before_process_nonce' )){
wp_send_json_error('Invalid nonce');
die();
}
$message = ['type'=>'success','message'=>'True'];
wp_send_json_success($message);
wp_die();
}
?>