0

I have a controller class called Index that is called in a javascript AJAX request, but rather than have the code in the constructor i would like to call specific functions in the Index.php, so i dont have to create a seperate class for every required function. Is it possible to call SavePricingChanges function from javascript?

Vendor/Pricing/Controller/Adminhtml/Ajaxcontroller/Index.php

<?php
namespace Vendor\Pricing\Controller\Adminhtml\Ajaxcontroller;

use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Customer\Model\Session;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;
        /**
     * @var Session
     */
    private $customerSession;
   
    /**
     * @param JsonFactory $resultJsonFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        JsonFactory $resultJsonFactory,
        Session $customerSession
    ) {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->customerSession = $customerSession;
    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        
    }

    public function SavePricingChanges(){
        $response = $this->resultFactory
             ->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
             ->setData([
                 'status'  => "success",
                 'message' => "form submitted correctly"
             ]);

        return $response;  
    }
}

etc/adminhtml/routes.xml

 <?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="admin">
            <route id="adminpath" frontName="adminpath">
                <module name="Vendor_Pricing" />
            </route>
        </router>
    </config>

my javascript in the phtml file

<script type="text/javascript">
    require(["jquery"],function($) {
        $('#savePricing').click(function() {
            var customurl = "<?php echo $block->getUrl('adminpath/ajaxcontroller'); ?>";
            $.ajax({
                url: customurl,
                type: 'POST',
                dataType: 'json',
                data: {form_key: window.FORM_KEY},
                showLoader: true,
            complete: function(response) {             
                var status = response.responseJSON.status;       
                   if(status == "success"){
                        //there is a response from index.php
                   }   
                },
                error: function (xhr, status, errorThrown) {
                    console.log('Error happens. Try again. error : ' + errorThrown);
                }
            });
        });
    });
</script>

I can get a response if i put the code from Index.php in the constructor but i need to call specific functions

1 Answer 1

0

Magento 2 controller has execute method which only gets called.

For your application you can create a separate class (a block or helper) that handles the logic you want In the existing controller, you can inject that class & call its methods.

Below is the example :-

class Index extends \Magento\Framework\App\Action\Action
{
     protected $helperData;

     public function __construct(
          \Magento\Framework\App\Action\Context $context,
          \{Vendor}\{Module}\Helper\Data $helperData
     ){
           $this->helperData = $helperData;
           parent::__construct($context, $helperData);
     }

     public function execute()
     {
           $this->helperData-><functionName>();
           return;     
     }
}

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.