PeterJohn Hunt

Basic AJAX in WordPress

Sample code repo

1) Setup Form

<form action="">
    <input type="text" name="email">
    <input type="hidden" name="action" value="my-action">
    <button type="submit">Submit</button>
</form>

2) Setup Javascript

Add localize script:

wp_localize_script( 'theme-javascript', 'AJAX', [
    'URL' => admin_url('admin-ajax.php')
]);

global comment:

/* global AJAX */

Add form submission handler

$form.submit(function(e) {
    e.preventDefault();

    $.post(AJAX.URL, $form.serialize(), function(res) {
        if ( !res.success ) {
            console.log( res );
            return;
        }
        
        // success
        console.log( res );
    });
});

3) Setup AJAX Handlers

function handle_my_action() {
    $email = $_POST['email'];

    wp_send_json_success($email);
}
add_action('wp_ajax_my-action', 'handle_my_action');
add_action('wp_ajax_nopriv_my-action', 'handle_my_action');