Custom Shortcode AJAX 400 Bad Request

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);
        });
    }
});

Leave a Comment