In this tutorial we will see how to send data to Controller and return Result to PHTML.

To understand more about ajax in magento 2 or magento 2 create ajax controller we will do practice.

Lets do this practically, you need to follow step by step

Step 1: Create a new module called Techone_AjaxTutorial : Ajax call magento 2

  • Create the namespace Techone in the path app\code.
  • Create the module name Ajaxtutorial in the path app\code\Techone.
  • Create the file named registration.php in the path app\code\Techone\Ajaxtutorial
<?php use \Magento\Framework\Component\ComponentRegistrar;ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Techone_Ajaxtutorial', __DIR__);

Create the file name module.xml in the path app\code\Techone\Ajaxtutorial\etc

<?xml version="1.0"?><config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Techone_Ajaxtutorial" > </module></config>

End of step #1, I have been completed the step to create new module called Techone_Ajaxtutorial

Step 2: Declare Route : Ajax call magento 2

  • Route will define name for a module which can use in url to find the url and execute the controller action.
  • Create the new file named routes.xml in the path app\code\Techone\Ajaxtutorial\etc\frontend
  • I put the routes.xml file in the folder named frontend, because I want these codes only to apply on the storefront.
<?xml version="1.0"?><config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="standard"> <route id="ajaxtutorial" frontName="ajaxtutorial"> <module name="Techone_Ajaxtutorial" /> </route> </router></config>

Step 3: Declare Layout

  • The Layout is the major path of view layer in Magento 2 module.The layout file is a XML file which will define the page structure and will be locate in Techone\Ajaxtutorial\view\frontend\layout\ folder.
  • When rendering page, Magento will check the layout file to find the handle for the page and then load Block and Template. We will create a layout handle file for this module.
  • Create the new file named ajaxtutorial_index_index.xml, one more ajaxtutorial_result_result.xml
In the path app\code\Techone\Ajaxtutorial\view\frontend\

I put the layout xml file in the folder named frontend, because I want these codes only to apply on the storefront.

Layout 1: ajaxtutorial_index_index.xml

<page xmlns:xsi="" layout="1column"xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <title>Addition Using Ajax</title> </head> <body> <referenceContainer name="content"> <block class="Techone\Ajaxtutorial\Block\Index" name="calculation_index" template="Techone_Ajaxtutorial::calculation.phtml" /> </referenceContainer> </body></page>

Layout 2 : ajaxtutorial_result_result.xml (for getting result)

<page xmlns:xsi="" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <title>Result</title> </head> <body> <referenceContainer name="content"> <block class="Techone\Ajaxtutorial\Block\Index" name="result_result" template="Techone_Ajaxtutorial::result.phtml" /> </referenceContainer> </body></page>

Step 4 : Declare Template

  • In the template file, we can use the html consist for form in which we are passing two number using input field with button,also we add jquery ajax below script on click of button we use ajax , we also use more template file in which we use variable $block for the block object.
  • Create the new file named calculation.phtml
Path app\code\Techone\Ajaxtutorial\view\frontend\templates\- Create one more the new file named result.phtml - The path app\code\Techone\Ajaxtutorial\view\frontend\templates

Template 1 : calculation.phtml

<div class="row clearfix"> <div class="col-md-12 column"> <form name="form_value" method="POST" id="form_value"> <label>Number one</label> <input type="text" name="numone" class="form-control input-md" style="margin:20px;width:300px;" autocomplete="off"> <label>Number two</label> <input type="text" name="numtwo" class="form-control input-md" style="margin:20px;width:300px;" autocomplete="off"> <input type="submit" id="calculateTotalSubmit" name="calculate-total-submit" value="Calculate Total"> </div> </form><br/><br/> Result<div class="result" style="display:none"></div> </div> </div><script>require(['jquery'],function(){ jQuery(document).ready(function() { jQuery(".result").hide(); jQuery("#form_value").submit(function(){ var oneValue = jQuery("input[name='numone']").val(); var twoValue = jQuery("input[name='numtwo']").val(); var url = "<?php echo $block->getBaseUrl().'ajaxtutorial/result/result/' ?>"; jQuery.ajax({ url: url, type: "POST", data: {numone:oneValue,numtwo:twoValue}, showLoader: true, cache: false, success: function(response){ console.log(response.output); jQuery(".result").show(); jQuery(".result").text(response.output); } }); return false; }); });});</script>

Template 2 : result.phtml

<?php $h = $block->getNumoneData(); $w = $block->getNumtwoData(); echo $total = $h + $w;?>

Step 5 : Declare Controller (magento 2 ajax controller)

  • As a class located in module controller folder.
  • Controller is responsible for specific URL.
  • Create the new file named Index.php
Path app\code\Techone\Ajaxtutorial\Controller\Index
<?phpnamespace Techone\Ajaxtutorial\Controller\Index;use \Magento\Framework\App\Action\Action;use \Magento\Framework\App\Action\Context;use \Magento\Framework\View\Result\PageFactory;class Index extends Action{ /** * @var PageFactory */ protected $resultPageFactory; /** * Result constructor. * @param Context $context * @param PageFactory $pageFactory */ public function __construct(Context $context, PageFactory $pageFactory) { $this->resultPageFactory = $pageFactory; parent::__construct($context); } /** * The controller action * * @return \Magento\Framework\View\Result\Page */ public function execute() { $resultPage = $this->resultPageFactory->create(); return $resultPage; }}

Create the new file named Result.php.

In the path app\code\Techone\Ajaxtutorial\Controller\Result
<?phpnamespace Techone\Ajaxtutorial\Controller\Result;use Magento\Framework\App\Action\Context;use Magento\Framework\View\Result\PageFactory;use Magento\Framework\Controller\Result\JsonFactory;class Result extends \Magento\Framework\App\Action\Action{ /** * @var Magento\Framework\View\Result\PageFactory */ protected $resultPageFactory; protected $resultJsonFactory; /** * @param Context $context * @param PageFactory $resultPageFactory */ public function __construct( Context $context, PageFactory $resultPageFactory, JsonFactory $resultJsonFactory ) { $this->resultPageFactory = $resultPageFactory; $this->resultJsonFactory = $resultJsonFactory; return parent::__construct($context); } public function execute() { $numone = $this->getRequest()->getParam('numone'); $numtwo = $this->getRequest()->getParam('numtwo'); $result = $this->resultJsonFactory->create(); $resultPage = $this->resultPageFactory->create(); $block = $resultPage->getLayout() ->createBlock('Techone\Ajaxtutorial\Block\Index') ->setTemplate('Techone_Ajaxtutorial::result.phtml') ->setData('numone',$numone) ->setData('numtwo',$numtwo) ->toHtml(); $result->setData(['output' => $block]); return $result; } }

Step 6 : Declare BlockAjax call in magento 2

  • The Block file contain all the view logic required it is important.
  • It should not contain any kind of html or css.
  • In this file are supposed to have all application view logic.
  • Create the new file named Index.php.
In the path app\code\Techone\Ajaxtutorial\Block\Index
<?phpnamespace Techone\Ajaxtutorial\Block;use \Magento\Framework\View\Element\Template;use \Magento\Framework\View\Element\Template\Context;class Index extends Template{ public function __construct(Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager ) { $this->_storeManager = $storeManager; parent::__construct($context); } public function getBaseUrl() { return $this->_storeManager->getStore()->getBaseUrl(); } public function getNumoneData() { return $this->getNumone(); } public function getNumtwoData() { return $this->getNumtwo(); }}

Step 4: Test and see the results Ajax call in magento 2

Run the command lines following:php bin/magento setup:upgradephp bin/magento setup:static-content:deploy -fphp bin/magento cache:flush -doneGo to ajax url page and check result

Get source code:

Below video tutorial you will see all step by setp Ajax call in magento 2

Magento 2 Ajax Tutorial