Using a PHP variable in JavaScript is the easier way to go. You can just define a new variable using var, let or const, and use PHP to output the value:
$value = 5;
add_action( 'wp_footer', function () use ( $value ) { ?>
<script>
document.addEventListener('DOMContentLoaded', () => {
const button = document.querySelector("#tester");
const value = <?php echo esc_js( $value ); ?>;
button.addEventListener('click', () => {
alert(value); // trying to retain the value 5
});
}
);
</script>
<?php
} );
If your value is a string, make sure you include quotation marks around the PHP statement, and if it’s a more complex type like an array, then I recommend using the wp_json_encode function to convert it to JavaScript syntax.
Sending a variable value back from JavaScript to PHP is a little more difficult. You would need to use something like AJAX to send the value to a different page, where you can write a function to intercept the value and do something with it. You can find a guide to using AJAX on the WordPress Plugin Handbook.
Hi Shea,
It turns out I may also need to move values back from JavaScript to PHP. I wrote the following functions in two separate snippets:
add_action( 'wp_footer', function () { ?>
<script>
document.addEventListener('DOMContentLoaded', ( ) => {
const button = document.querySelector("#tester");
button.addEventListener('click', () => {
var data = {
'action' : 'my_action',
'function' : ajax_object.we_value
};
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
</script>
<?php
});
and:
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}
wp_enqueue_script( 'ajax-script', plugins_url( 'record_clicks', __FILE__ ), array('jquery') );
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 0 ) );
}
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action(){
echo 'Ajax call output:';
$function = intval( $_POST['function'] );
$function += 1;
echo '<pre>';
echo $funciton;
echo '</pre>';
wp_die();
}
When I call wp_enque_script, “record_clicks” is the name of my other snippet. I don’t think the values are being passed correctly and my alert isn’t activating. Any insight you have would be greatly appreciated. Thanks.
Hi @dixon3al, apologies for not getting back to this until now. Just checking if you ended up getting your code working or if you would still like some assistance?