How To Make An Ajax Request In WordPress With Admin-Ajax.php
Register a PHP handler with the wp_ajax_ and wp_ajax_nopriv_ hooks, then call it from JavaScript with fetch(). This example requires the lotgrafixData object from the wp_localize_script() post.
functions.php
function lotgrafix_ajax_handler() {
check_ajax_referer( 'lotgrafix_nonce', 'nonce' );
$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
wp_send_json_success( array( 'message' => 'Hello ' . $name ) );
}
add_action( 'wp_ajax_lotgrafix_action', 'lotgrafix_ajax_handler' );
add_action( 'wp_ajax_nopriv_lotgrafix_action', 'lotgrafix_ajax_handler' );
main.js
fetch( lotgrafixData.ajaxUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams( {
action: 'lotgrafix_action',
nonce: lotgrafixData.nonce,
name: 'Lotgrafix',
} ),
} )
.then( ( r ) => r.json() )
.then( ( res ) => console.log( res.data.message ) );
November 3, 2026


