0

I am writing a plugin (in PHP) that outputs an array.

The resulting array should be the input for some JavaScript file that outputs a chart (.png image) based on the array.

With this in mind, I should pass variables to JavaScript from the PHP plugin (as seen here).

I wonder if the process with a plugin is different from an ordinary PHP file...

The JS chart should be displayed according to user action.


In a nutshell:

How can I call the JS file, pass a variable to it via an ordinary plugin?

2
  • Note that PHP doesn't call JS, rather JS either finds the data is already on the page, or JS makes a request to the server to retrieve it. Think of it as mission control and lunar astronauts. The PHP factory builds the space shuttle, and the JS astronauts operate it when it lands. The factory can't rely on objects on the moon being moved by JS astronauts, they're still on earth waiting to be launched. You can send supplies with them but once they're sent they're sent. Once the astronauts are there they have to radio home to request a new supply shuttle
    – Tom J Nowell
    Commented Aug 27, 2018 at 22:57
  • Thank you for this elucidating analogy! Still, do you know if the methods used to "send supplies" from an ordinary PHP file are still the same for a wp-plugin? Many thanks for considering my question.
    – nickh
    Commented Aug 27, 2018 at 23:57

1 Answer 1

2

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.