Minimal AJAX in WordPress

Minimal AJAX in WordPress

David Nash code, php Leave a Comment

Here’s what it takes to create minimal AJAX in WordPress. First, let’s create a button:

<button id="ajax_button">Click me</button>

Then functions.php include a Javascript file called do_ajax.js. It has the dependencies jquery and wp-util:

wp_enqueue_script('base', get_stylesheet_directory_uri().'/js/do_ajax.js', ['jquery', 'wp-util'], false, 'footer' );

Also in functions.php, we set up a function to handle the AJAX call, and add the actions:

function handle_ajax() {
    if (isset($_POST['the_data'])) {
        wp_send_json_success($_POST['the_data']);
    }
}
add_action('wp_ajax_nopriv_handle_ajax', 'handle_ajax');
add_action('wp_ajax_handle_ajax', 'handle_ajax');

Finally, in our do_ajax.js file:

$(document.ready(function() {
    $('#ajax_button').click(function() {
        wp.ajax.post('handle_ajax', {'the_data': 'Hello!'})
            .done(function(response) {
                console.log(response);
            }
    }
});

And then in your console you should see “Hello!”.

That string is being sent from do_ajax.js to the server, and the server simply sends it back again.

That’s it – we have minimal AJAX in WordPress up and running! This post was based on this StackOverflow answer, and is intended as a much less detailed post than my Autocomplete with AJAX in WordPress article.

Hopefully from here you can build whatever you like!

Leave a Reply

Your email address will not be published. Required fields are marked *