I'm writing a custom shortcode that will need to call some PHP file via AJAX, after some user event. But I am getting Bad Request 400 as if my wp_ajax_*
actions aren't being bound.
Here is a simple sample of my plugin code
function aj_ajax_demo_shortcode() {
return '<h4>Shortcode</h4>';
}
add_shortcode( 'ajax_demo', 'aj_ajax_demo_shortcode' );
add_action( 'wp_ajax_nopriv_aj_ajax_demo', 'aj_ajax_demo_process' );
add_action( 'wp_ajax_aj_ajax_demo', 'aj_ajax_demo_process' );
function aj_ajax_demo_process() {
wp_send_json((object) array('msg' => 'hello world'));
}
add_action( 'wp_enqueue_scripts', 'aj_enqueue_scripts' );
function aj_enqueue_scripts() {
wp_enqueue_script(
'aj-demo',
plugin_dir_url( __FILE__ ) . 'aj-demo-ajax-code.js'
);
wp_localize_script(
'aj-demo',
'aj_ajax_demo',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'aj_demo_nonce' => wp_create_nonce('aj-demo-nonce')
)
);
}
And here is my JS:
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
data: {
action : 'aj_ajax_demo',
nonce : aj_ajax_demo.aj_demo_nonce,
}
}).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
}
});
As far as I have researched, I am doing things in the correct order, so no idea why my AJAX function isn't being called. Is there something I'm missing because this is a shortcode?