Roots Discourse

Right way to create an Ajax Class in Sage 10?

Hello there, I’m trying to create, in the right way, a class to do a simple return of a Title Post call in Ajax.

This is the far I get:

app/setup.php

add_action('wp_enqueue_scripts', function () {
    wp_enqueue_script('sage/vendor.js', asset('scripts/vendor.js')->uri(), ['jquery'], null, true);
    wp_enqueue_script('sage/app.js', asset('scripts/app.js')->uri(), ['sage/vendor.js'], null, true);
    // + Localize script /Providers/Ajax
    wp_localize_script('sage/app.js', 'sage', Providers\Ajax::localize_script_vars());

app/Providers/Ajax.php (new file - removed comments)

<?php
namespace App\Providers;
class Ajax
{
    function __construct()
    {
        $this->add_ajax_actions();
    }
    public function add_ajax_actions()
    {
        add_action('wp_ajax_nopriv_test', array($this, 'test'));
        add_action('wp_ajax_test', array($this, 'test'));
    }
    public static function localize_script_vars()
    {
        return  [
            'admin_url' => admin_url('admin-ajax.php')
        ];
    }
    public function test()
    {
        wp_send_json('it works');
    }
};

app/helpers.php

<?php
/**
 * Theme helpers.
 */
namespace App;
new \App\Providers\Ajax;

resources/scripts/app.js (just a test script)

[..]
let data = {
  'action': 'test',
};
var request = new XMLHttpRequest();
request.open('POST', sage.admin_url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function () {
  if (request.status >= 200 && request.status < 400) {
    console.log(request.response);
  }
};
request.send(new URLSearchParams(data));

And everything works great. But I want a second opinion if I’m on the right direction, or if there’s a “fancy” way to achieve that.

Thanks for any kind of help.