2

I am trying to fetch input value but I am unable to get values in the controller. Here is my code,

Controller\Index\Index.php

<?php

namespace Crud\Crudatfrontend\Controller\Index;

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

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory
        )
    {
        $this->_pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {   
        return $this->_pageFactory->create();       
    }
}

Controller\Result\Result.php

<?php

namespace Crud\Crudatfrontend\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()
    {
        //echo '<pre>';
        //print_r($this->getRequest('height')->getParams());exit;
        $height = $this->getRequest()->getParam('height');

        if (isset($height)) { 

        echo $height; exit();

        } 
        else{
            echo "not found";
        }



        $weight = $this->getRequest()->getParam('weight');
        $result = $this->resultJsonFactory->create();
        $resultPage = $this->resultPageFactory->create();

        $block = $resultPage->getLayout()
                ->createBlock('Crud\Crudatfrontend\Block\Index')
                ->setTemplate('Crud_Crudatfrontend::result.phtml')
                ->setData('height',$height)
                ->setData('weight',$weight)
                ->toHtml();

        $result->setData(['output' => $block]);
        return $result;
    } 
}

view\frontend\layout\crud_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Crud\Crudatfrontend\Block\Index" name="crud_index_index" template="Crud_Crudatfrontend::index.phtml" />
    </referenceContainer>
</page>

view\frontend\layout\crud_result_result.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Crud\Crudatfrontend\Block\Index" name="crud_result_result" template="Crud_Crudatfrontend::result.phtml" />
    </referenceContainer>
</page> 

view\frontend\templates\index.phtml

<div class="row clearfix">
            <div class="col-md-12 column">
                <form name="form_height" method="POST" id="form_height">
                       height <input type="text" name="height" class="form-control input-md">
                       weight <input type="text" name="weight" class="form-control input-md">
                        <input type="submit" id="calculateTotalSubmit"  name="calculate-total-submit" value="Calculate Total">
                    </div> 
                </form>
            </div>
        </div>


    <script>
    require(['jquery'],function(){
        jQuery(document).ready(function() {


            jQuery("#form_height").submit(function(){

                var heightValue = jQuery("input[name='height']").val();
                var weightValue = jQuery("input[name='weight']").val();

                var url = "<?php echo $block->getBaseUrl().'crud/result/result/' ?>";
                jQuery.ajax({
                url: url,
                type: 'POST',
                data: {height:heightValue,weight:weightValue},

                success: function(response){
                    console.log(response.output);
                    window.location.href = url;
                }
                       });
            return false;
            });
        });
    });
    </script>

view\frontend\templates\result.phtml

<?php 

    echo $block->getHeightData();
    echo $block->getWeightData();

?>

Block/Index.php

<?php

namespace Crud\Crudatfrontend\Block;

use Magento\Framework\App\Filesystem\DirectoryList;
use \Magento\Framework\View\Element\Template;
use \Magento\Framework\View\Element\Template\Context;

class Index extends \Magento\Framework\View\Element\Template
{
    protected $_filesystem;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
         \Magento\Store\Model\StoreManagerInterface $storeManager
        )
    {           
         $this->_storeManager = $storeManager;
        parent::__construct($context);
    }   


    public function getBaseUrl()
    {
        return $this->_storeManager->getStore()->getBaseUrl();
    }

    public function getHeightData()
    {
        return $this->getHeight();
    }

    public function getWeightData()
    {
        return $this->getWeight();
    }
}

1 Answer 1

0

First you need to add form key

<form name="form_height" method="POST" id="form_height">
    <div>
        <input type="hidden" name="form_key" value="<?php echo $block->getFormKey() ?>" />
       height <input type="text" name="height" class="form-control input-md">
       weight <input type="text" name="weight" class="form-control input-md">
        <input type="submit" id="calculateTotalSubmit"  name="calculate-total-submit" value="Calculate Total">
    </div> 
</form>

Secondly, use serialize to get all the data in your from when calling ajax

<script>
require(['jquery'],function(){
    jQuery(document).ready(function() {


        jQuery("#form_height").submit(function(){

            var heightValue = jQuery("input[name='height']").val();
            var weightValue = jQuery("input[name='weight']").val();

            var url = "<?php echo $block->getBaseUrl().'crud/result/result/' ?>";
            jQuery.ajax({
            url: url,
            type: 'POST',
            data: jQuery(this).serialize(),

            success: function(response){
                console.log(response.output);
                window.location.href = url;
            }
                   });
        return false;
        });
    });
});
</script>

This should resolve your issue

4
  • I have added echo "not found" in the controller, still getting the same msg like before Apr 11, 2019 at 11:17
  • use echo "<pre>"; print_r($_POST); echo "</pre>"; die; in your controller and check if you are getting post variable Apr 11, 2019 at 11:20
  • Before changes, I was getting values in the console, now I am getting undefined in the console Apr 11, 2019 at 11:23
  • print_r($_POST); this is printing array() Apr 11, 2019 at 11:23

Your Answer

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

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