Yes. You can do. Try using ajax, or better? using wordpress rest api
Ajax method: need register your function and action to do
Simple example:
add_action( 'wp_ajax_my_action', 'my_action' );
function my_actionadd_action() {
return'wp_ajax_nopriv_my_action', json_encode('hello'my_action' word');
}
<script>
jQuery(document).ready(function($) {
var data = {
'action': 'my_action'
};
jQuery.post(ajax_url, data, functionmy_action(response) {
return alertjson_encode(response);
'hello }word');
});
</script>
jQuery(document).ready(function() {
var data = {
'action': 'my_action'
};
jQuery.post(ajax_url, data, function(response) {
alert(response);
});
});
More info for ajax: https://codex.wordpress.org/AJAX_in_Plugins
Wordpress rest api: need to register a route
very simple example:
add_action( 'rest_api_init', function () {
register_rest_route( 'yourName/v1', '/myroute', array(
'methods' => 'GET''POST',
'callback' => 'my_function',
) );
} );
function my_function( $data ) {
return 'Hello World';
}
jQuery(document).ready(function() {
jQuery.post('/wp-json/yourName/v1/myroute', function(response) {
alert(response);
});
});
More info: https://developer.wordpress.org/rest-api/