After going through a lot of articles and solutions I finally figured it out:
Directory Structure for the plugin (Boilerplate directory structure used from here)
First step:
Register a js
script which would track the event/ user activity and pass it the ajax URL through which it would fetch the product details via ajax.
// admin/class-pluginname-admin.php or public/class-pluginname-public.php
function register_my_scripts(){
wp_register_script('script_alias', ...);
wp_localize_script('script_alias', 'localParams', array('ajax_url'=>admin_url('admin-ajax.php')));
wp_enqueue_script('script_alias');
}
Second:
Create a js
file which would make an ajax call when the trigger occurs.
// event-js-file.js
...
$.ajax({
url: localParams.ajax_url,
type: "POST",
data:{
action: "my_custom_action", // calling the custom ajax action
// send data via this post request
},
success: function(res){// success response of the request},
error: function(err){// error as response of the request}
});
Third:
Create a custom ajax action which would respond to the request made via the js file and give the required data.
// includes/class-pluginname.php
add_action('wp_ajax_my_custom_action', 'my_custom_function', priority_value);
add_action('wp_ajax_nopriv_custom_action', 'my_custom_function', priority_value);
add_action('wp_enqueue_scripts', 'register_my_scripts', priority_value);
// admin/class-pluginname-admin.php or public/class-pluginname-public.php
function my_custom_function(){
// This is called via the js file ajax call.
// Calculate or generate or resolve the data necessary and send the
// response to the js script.
}