Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active May 29, 2018 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjbrum/af75663acef1c9f4426d85784985bfc2 to your computer and use it in GitHub Desktop.
Save kjbrum/af75663acef1c9f4426d85784985bfc2 to your computer and use it in GitHub Desktop.
Quick example of how to use AJAX with WordPress.

WordPress Ajax

Template

<form class="form">
    <label for="password">Password</label>
    <input name="password" type="password">
    <?php wp_nonce_field( 'password_check_form' ); ?>
    <input type="submit" class="btn" value="Download">
</form>

main.js

$('.form').on('submit', function(e) {
    e.preventDefault();
    checkPassword();
});

// Check the form password with ajax
function checkPassword() {
    $.ajax({
        cache: false,
        dataType : 'json',
        url: WP.ajax_url,
        type: 'GET',
        data: {
            action: 'check_form_password',
            nonce: $('.form input[name="_wpnonce"]').val(),
            password: $('.form input[name="password"]').val()
        },
        error: function(response, textStatus, errorThrown) {
            console.log(response);
            console.log('Error: Something went wrong, please try again.');
        },
        success: function(response, textStatus, jqXHR) {
            console.log(response);

            if (response.success) {
                console.log('Success: The password is correct.');
            } else {
                console.log('Error: ' + response.data.error);
            }
        }
    });
}

functions.php

// Load JS in the footer
wp_enqueue_script( 'main-js', get_template_directory_uri().'/js/main.min.js', array(), filemtime( get_template_directory().'/js/main.min.js' ), true );

// Get the admin ajax url
wp_localize_script( 'main-js', 'WP', array(
    'ajax_url' => admin_url( 'admin-ajax.php' )
));

// Check if a form password matches the master password.
function check_form_password() {
    // Verify our nonce
    if ( ! wp_verify_nonce( $_GET['nonce'], 'password_check_form' ) ) {
        // Return an error
        echo wp_send_json_error(array(
            'error' => 'Unable to verify this was a safe request.'
        ));
        exit;
    }

    // Get the user inputted password
    $user_password = filter_var( $_GET['password'], FILTER_SANITIZE_STRING );

    // Get the master password to check against
    $correct_password = get_field( 'master_password', 'options' );

    // Check if the password is correct
    if ( $user_password == $correct_password ) {
        echo wp_send_json_success();
        exit;
    }

    // Return an error
    echo wp_send_json_error(array(
        'error' => 'The password you entered is incorrect.'
    ));
    exit;
}
add_action( 'wp_ajax_check_form_password', 'check_form_password' );
add_action( 'wp_ajax_nopriv_check_form_password', 'check_form_password' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment