Sage 10 Ajax Bad Request

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.

I recommend you look into using the Rest API instead.

That aside, what is this.action_load_posts equal? Does it work if you just pass { action: 'load_posts' }? 400 is generally going to get returned when WordPress doesn’t understand your request (e.g. no action exists).

Are you sure your Ajax class is getting autoloaded? Generally you’d want to put this stuff inside of an mu-plugin or a Service Provider. For sanity purposes, I’d maybe throw your hook into filters.php or something before abstracting it.

At the moment there are multiple possible points of failure. If the above doesn’t work, maybe $.ajax? I’m not really sure. I haven’t used either jQuery or the Ajax stuff in WordPress in a very long time.

Thanks @Log1x. It turned out that I needed to add ‘ajax’ to the array passed to the collect function inside of functions.php. You’re response helped me track down the issue though because it made me look at why the Ajax class was not being loaded.

I appreciate the quick response. Cheers.

1 Like

I had the same problem. I solved it by adding the following header: 'Content-Type': 'application/x-www-form-urlencoded'

1 Like