This the script you need to add on your phtml file:
<script type="text/javascript">
require(['jquery','underscore'], function(jQuery,_){
jQuery(window).load(function(){
jQuery( ".product-options-wrapper div" ).click(function() {
selectedProduct();
});
});
function selectedProduct() {
var selected_options = {};
jQuery('div.swatch-attribute').each(function(k,v){
var attribute_id = jQuery(v).attr('attribute-id');
var option_selected = jQuery(v).attr('option-selected');
if(!attribute_id || !option_selected){ return;}
selected_options[attribute_id] = option_selected;
});
var product_id_index = jQuery('[data-role=swatch-options]').data('mageSwatchRenderer').options.jsonConfig.index;
var found_ids = [];
jQuery.each(product_id_index, function(product_id,attributes){
var productIsSelected = function(attributes, selected_options){
return _.isEqual(attributes, selected_options);
}
if(productIsSelected(attributes, selected_options)){
console.log(product_id);
jQuery.ajax({
url: "<?php echo $block->getUrl('getsku'); ?>",
type: "POST",
data: {id:product_id},
showLoader: false,
cache: false,
success: function(response){
console.log(response);
}
});
}
});
}
});
</script>
Create a module with name Vendor_Module.
Also you need to create a routes.xml for frontend like below:
app/code/Vendor/Module/etc/frontend/routes.xml
and add the following code to it.
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route frontName="getsku" id="getsku">
<module name="Vendor_Module"/>
</route>
</router>
</config>
Now create one controller to below path:
app/code/Vendor/Module/Controller/Index/Index.php
with below content:
<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
class Index extends Action
{
protected $_productRepository;
public function __construct(
Context $context,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository
)
{
$this->_productRepository = $productRepository;
parent::__construct($context);
}
public function execute()
{
$id = $this->getRequest()->getParam('id');
echo $this->_productRepository->getById($id)->getSku();
}
}
You will get the sku in your ajax response. You can now do whatever you want with the sku.
Hope this helps!