The WordPress way of handling AJAX requests is to use a specially constructed hook name built from the ‘action’ property of your AJAX request prepended with ‘wp_ajax_’ or ‘wp_ajax_nopriv_’.
In a namespaced setup (like Roots\Sage) you’d set up hooks and callbacks like this:
In this case, when you send an AJAX request to WordPress with a request ‘action’ property set to ‘my_custom_action’ the hook callback will be automatically executed.
Simplified manifest.json, adding test.js to our build directory:
Next up, enqueue the script. Sage provides a useful helper function to access the file path: Roots\Sage\Assets\asset_path(). Depending on the location of your enqueuing script, you may need to import the namespace.
Enqueuing from /lib/extras.php might look like this:
A simple jQuery AJAX handler might look like this:
This is designed to take and submit data from an on-page form that might look like this:
This example is just a stripped down version - mainly it’s a memory jogger for the hook name setup. I would generally build this functionality in an Object Oriented context - so the callbacks would be held within class methods rather than the functions shown here.