Hello, I am setting up ajax with my Sage 10 project. I keep getting a 400 Bad Request error. I have done this on many projects before but never with sage 10. I’ve searched the forum and many other resources and can’t seem to figure out what my problem is.
My files are as follows:
app/setup.php - localizing ajax_url
add_action('wp_enqueue_scripts', function () {
global $post;
bundle('app')->enqueue()->localize('wcu', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce'),
'post_id' => (isset($post->ID) ? $post->ID : null),
'posts_per_page' => get_option('posts_per_page'),
]);
}, 100);
app/ajax.php
<?php
namespace App;
class Ajax
{
public function __construct()
{
add_action('wp_ajax_load_posts', [$this, 'load_posts']);
add_action('wp_ajax_nopriv_load_posts', [$this, 'load_posts']);
}
public function load_posts()
{
echo "TEST";
exit;
}
}
new Ajax();
resources/scripts/app.js
let data = {
action: this.action_load_posts,
};
$.post(wcu.ajax_url, data, function(html) {
console.log(html);
} );
The wcu.ajax_url is localized and available in the javascript file. When I look at the request being made in my developer console I see it passing action : load_posts. The response tab in the console just shows 0 and this is the error message:
XHRPOST
http://mywebsite.local/wp-admin/admin-ajax.php
[HTTP/1.1 400 Bad Request 24ms]
Any help would be greatly appreciated.