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 = []

    public function process()
        // Return image path here to Jquery Ajax;

    protected function _toHtml()
        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 -->  

<script type="text/javascript">
     require(['jquery'], function(jQuery){ 
         jQuery("button").on('click', function() {
              type: "POST",
              url: "<URL_PATH_TO_CUSTOM_PROCESS_BLOCK_ACTION>"                
            }).done(function(o) {

            return false;

How can I call the block action from a JQuery Ajax?

1 Answer 1


You will have to use the url of a controller which uses a block to render output.

You've got a couple of options

Render json - jquery is quite good at reading this


And your jquery will look a bit like this


Or render markup direct in controller. Again you will have to code jquery to understand this

public function execute()
    $output = $this->layoutFactory->create()
    $resultRaw = $this->resultRawFactory->create();
    return $resultRaw->setContents($output);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.