extends | title | group | subgroup | prev | next | order |
---|---|---|---|---|---|---|
docs |
Defining AJAX responses |
Basics |
Http |
registering-stylesheets-and-scripts |
theme-actions |
2 |
WordPress gives you an ability to define various AJAX actions, which you can afterward hit with HTTP requests in order to create dynamic JavaScript components for your theme.
Your ajax listeners should be registered inside app/Http/ajaxes.php
file.
Please refer to the Codex documentation for comprehensive guides about creating AJAX actions.
Your scripts need to know an URL endpoint, where they can reach your registered actions. Start with providing an Admin AJAX URL, by localizing your script with data. Use admin_url()
function to pull URL for AJAX calls.
wp_register_script('script-ajax', asset_path('js/script-ajax.js'), ['jquery'], null, true);
wp_localize_script('script-ajax', 'Ajax', [
'ajax' => [
'url' => admin_url('admin-ajax.php')
],
]);
wp_enqueue_script('script-ajax');
Register listener for your AJAX action.
namespace Tonik\Theme\App\Http;
function handle_ajax_action()
{
// Action logic...
die();
}
add_action('wp_ajax_my_action', 'Tonik\Theme\App\Http\handle_ajax_action');
add_action('wp_ajax_nopriv_my_action', 'Tonik\Theme\App\Http\handle_ajax_action');
As an example, we will use $.ajax()
to perform an asynchronous HTTP request to our action endpoint.
import $ from 'jquery'
$.ajax({
url: Ajax.url,
dataType: 'json',
data: {
action: 'my_action' // Your AJAX action name
}
}).done(function(data, status, response) {
// Callback
})