I need to execute the Php function from my Ajax form with the POST method. Is there another way instead of ajax hooks?
Hooks doesn't execute. Always returning 0. What's wrong?
Here's my ajax.js
'use strict';
const url = test.ajaxUrl;
const data = {
action: 'ajax_request',
username: 'example'
};
async function Start(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log('Success:', JSON.stringify(json));
}
catch (error) {
console.error('Error:', error);
}
}
Start(url, data);
functions.php
add_action( 'wp_enqueue_scripts', 'enqueue_my_frontend_script' );
function enqueue_my_frontend_script() {
wp_enqueue_script( 'script-ajax', get_template_directory_uri() . '/assets/js/ajax.js', array(), null, true );
$variables = array(
'ajaxUrl' => admin_url( 'admin-ajax.php' )
);
wp_localize_script('script-ajax', "test", $variables);
}
function handle_ajax_request(){
$postData = file_get_contents('php://input');
$data = json_decode($postData);
echo json_encode($data);
die();
}
add_action("wp_ajax_ajax_request" , "handle_ajax_request");
add_action("wp_ajax_nopriv_ajax_request" , "handle_ajax_request");
action
parameter. See wordpress.stackexchange.com/questions/338787/…