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' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action() {
return json_encode('hello word');
}
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' => '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/