You can follow below steps:
HTMl Code:
<button id="clickMe" data-nonce="<?php echo esc_attr( wp_create_nonce( 'my-nonce' ) ); ?>">Click Me</button>
PHP Code: here you need to use wp_ajax
hook.
class myFunctions{
public function __construct(){
add_action( 'wp_ajax_clickme', [$this, 'ajax_callback']); // for logged in user only
add_action( 'wp_ajax_nopriv_clickme', [$this, 'ajax_callback']); // for non logged user only
}
public function ajax_callback() {
$test = "Hello World from wp_send_json()";
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'my-nonce' ) ) {
wp_send_json_error( 'Sorry, your nonce did not verify.' );
exit;
} else {
wp_send_json($test);
}
}
}
$run = new myFunctions();
JS Code: for your example, you can ignore nonce, name
import $ from "jquery";
class trigger {
constructor() {
this.button = $("#clickme");
this.events();
}
events() {
this.button.on("click", this.buttonHandler.bind(this));
}
buttonHandler() {
let ajax_url = "http://yoursite.com/wp-admin/admin-ajax.php";
$.ajax({
type: "post", // request type get, post
url: ajax_url, // this sould be http://yoursite.com/wp-admin/admin-ajax.php url
data: {
action: "clickme", // wp_ajax_$action or wp_ajax_nopriv_$action - Important
nonce: $(this).data('nonce'), // must pass wp nonce and verify to protect CSRF - Very Important for Security
name: "Razon", // your data, you can pass your own data like this - Optional
},
success: function(response) {
console.log(response);
}
});
}
}
Hope that help 🙂