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>

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) {

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

3) Setup AJAX Handlers

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

add_action('wp_ajax_my-action', 'handle_my_action');
add_action('wp_ajax_nopriv_my-action', 'handle_my_action');

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.