JavaScript in a PHP plugin

So the question and answer you linked to is still valid, the only part that changes is the AJAX part.

Specifically, there are now 2 options:

  • Admin AJAX API: A legacy API, most tutorials will use this, but it’s much harder to secure, and provides little to no help. If it isn’t implemented right you will have no clues as to why it isn’t working
  • REST API endpoints: These return JSON, and have significantly more support and helping structures. You can define the parameters you expect in a request and it’ll tell you if you didn’t include them, etc This is much easier and newer

e.g. lets add an endpoint:

add_action( 'rest_api_init', function () {
        register_rest_route( 'tomjn/v1', '/test/', array(
                'methods' => 'GET',
                'callback' => 'tomjn_rest_test'
        ) );
} );

This says, when a GET request is made to /wp-json/tomjn/v1/test call the function tomjn_rest_test to get the result:

function tomjn_rest_test( $request ) {
        return "moomins";
}

enter image description here

Which we can then fetch in javascript, here’s a jQuery example:

<script>
jQuery.ajax({
    url: <?php echo wp_json_encode( esc_url_raw( rest_url( 'tomjn/v1/test' ) ) ); ?>
}).done(function( data ) {
    jQuery( '#tomsword' ).text( data );
});
</script>