Basic question on passing variables to AJAX in WordPress

The simple answer: Don’t bother with the Admin AJAX API, use the REST API!

Tell WordPress about your endpoint:

add_action( 'rest_api_init', function () { // register dongsan/v1/whatever
        register_rest_route( 'dongsan/v1', '/whatever/', array(
                'methods' => 'POST', // use POST to call it
                'callback' => 'dongsan_whatever' // call this function
        ) );
} );

Now we have an endpoint at example.com/wp-json/dongsan/v1/whatever!

We told WordPress to run dongsan_whatever when it gets called, so lets do that:

function dongsan_whatever( \WP_REST_Request $request ) {
    $name = $request['name'];
    return 'hello '.$name;
}

Note that we used $request['name'] to get a name parameter!

So we have a URL:

example.com/wp-json/dongsan/v1/whatever

And we can send a POST request with a name to it and get some JSON back that says Hello ‘name’! So how do we do that?

Simples, it’s a standard jQuery post request:

jQuery.post(
    'https://example.com/wp-json/dongsan/v1/whatever',
    { 'name': 'Dongsan' }
).done( function( data ) {
    Console.log( data ); // most likely "Hello Dongsan"
} );

Further reading:

Leave a Comment