I would like to call an Action from a custom block that I created which is extending the \Magento\Catalog\Block\Product\View class. Now the idea here is that I will be clicking on the Add to cart button this will trigger an Jquery ajax request that process the form and upload an image. After the processing it will return the generated image back to the frontend (jquery ajax). This url will be used during the actual Add to cart
function is done. Below is my code
This is my Custom block from my Custom Module
namespace Custom\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
class ImageUploader extends \Magento\Catalog\Block\Product\View
{
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Framework\Url\EncoderInterface $urlEncoder,
\Magento\Framework\Json\EncoderInterface $jsonEncoder,
\Magento\Framework\Stdlib\StringUtils $string,
\Magento\Catalog\Helper\Product $productHelper,
\Magento\Catalog\Model\ProductTypes\ConfigInterface $productTypeConfig,
\Magento\Framework\Locale\FormatInterface $localeFormat,
\Magento\Customer\Model\Session $customerSession,
ProductRepositoryInterface $productRepository,
\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency,
array $data = []
)
{
parent::__construct(
$context,
$urlEncoder,
$jsonEncoder,
$string,
$productHelper,
$productTypeConfig,
$localeFormat,
$customerSession,
$productRepository,
$priceCurrency,
$data
);
}
public function process()
{
// Return image path here to Jquery Ajax;
}
protected function _toHtml()
{
$this->setModuleName($this->extractModuleName('Magento\Catalog\Block\Product\View'));
return parent::_toHtml();
}
}
Now in my .phtml template I'm using an JQuery Ajax to call this ImageUploader->process() function (I'm not sure if this is the correct approach)
Below is my code
<?php $_product = $block->getProduct(); ?>
<div id="personalise" class="personalise">
<div class="wrapper">
<h2>Personalise Your Label</h2>
<!--- SOme html structure here -->
</div>
</div>
<script type="text/javascript">
require(['jquery'], function(jQuery){
jQuery("button").on('click', function() {
jQuery.ajax({
type: "POST",
url: "<URL_PATH_TO_CUSTOM_PROCESS_BLOCK_ACTION>"
}).done(function(o) {
alert("DOne");
});
return false;
});
});
</script>
How can I call the block action from a JQuery Ajax?