Custom Shortcode AJAX 400 Bad Request

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The problem is that you’re attempting to use the arguments for the jQuery AJAX API with the native Fetch API. Specifically, the problem is that the JS Fetch API doesn’t support a data argument.

For an admin-ajax.php request to work in WordPress the $_REQUEST['action'] property needs to be populated, and to do this with the Fetch API you need to pass a FormData object to the body parameter:

var data = new FormData();

data.append( 'action', 'aj_ajax_demo' );
data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );

fetch(aj_ajax_demo.ajax_url, {
    method: 'POST',
    body: data,
}).then(response => {
    if (response.ok) {
        response.json().then(response => {
            console.log(response);
        });
    }
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x