Can anyone explain me how I can create a simple form on Magento-2 page to send data using Ajax?
I already have a form and controller action, that send data without using ajax.
Magento 2 – How to Send Data Using Ajax in Custom Form
ajaxmagento2
Related Solutions
your form phtml
<div class="content-header">
<table cellspacing="0" class="grid-header">
<tr>
<td><h3><?php echo $this->__('Import Tracking Number')?></h3></td>
<td class="a-right">
<button onclick="editForm.submit()" class="scalable save" type="button"><span>Import</span></button>
</td>
</tr>
</table>
</div>
<div class="entry-edit">
<form id="edit_form" name="edit_form" method="post" action="<?php echo $this->getUrl('*/*/import')?>" enctype="multipart/form-data">
<input name="form_key" type="hidden" value="<?php echo Mage::getSingleton('core/session')->getFormKey() ?>" />
<div class="entry-edit-head">
<h4 class="icon-head head-edit-form fieldset-legend"><?php echo $this->__('Import CSV File ')?></h4>
</div>
<fieldset id="my-fieldset">
<table cellspacing="0" class="form-list">
<tr>
<td class="label"><?php echo $this->__('Add CSV File to Import')?> <span class="required">*</span></td>
<td class="input-ele"><input type="file" class="input-text required-entry" name="csv" />
</td>
</tr>
</table>
</fieldset>
</form>
</div>
<script type="text/javascript">
var editForm = new varienForm('edit_form');
</script>
Controller code
public function importAction()
{
$File=$_FILES['csv']['name'];
$_FILES['csv']['type'];
$mimes = array('application/vnd.ms-excel','application/octet-stream','text/plain','text/csv','text/tsv');
if(in_array($_FILES['csv']['type'],$mimes)){
$absolute_path = Mage::getBaseDir('media') . DS .('massorderprocessing');
$relative_path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
// File Upload
$files = $_FILES['csv']['name'];
if(file_exists($absolute_path.DS.$files))
{
$var = rand(0,99);
$files = $var.'_'.$files;
}
$uploader = new Varien_File_Uploader('csv');
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->save($absolute_path, $files);
$csvObject = new Varien_File_Csv();
$data=$csvObject->getData($absolute_path.'/'.$files);
foreach($data as $dat)
{
//do your logic here
}
}
Calculation Layout -
Vendor/Module/view/frontend/layout/module_index_index.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Calculator</title>
</head>
<body>
<referenceContainer name="content">
<block class="Vendor\Module\Block\Index" name="calculation_index" template="Vendor_Module::calculation.phtml" />
</referenceContainer>
</body>
</page>
Calculation Input PHTML -
Vendor/Module/view/frontend/templates/calculation.phtml
<div class="row clearfix">
<div class="col-md-12 column">
<form name="form_height" method="POST" id="form_height">
<input type="text" name="height" class="form-control input-md">
<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().'module/result/result/' ?>";
jQuery.ajax({
url: url,
type: "POST",
data: {height:heightValue,weight:weightValue},
showLoader: true,
cache: false
success: function(response){
console.log(response.output);
}
});
return false;
});
});
});
</script>
Block -
Vendor/Module/Block/Index.php
<?php
namespace Vendor\Module\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 getHeightData()
{
return $this->getHeight();
}
public function getWeightData()
{
return $this->getWeight();
}
}
Calculation Controller -
Vendor/Module/Controller/Index/Index.php
<?php
namespace Vendor\Module\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;
}
}
Result Page Controller -
Vendor/Module/Controller/Result/Result.php
<?php
namespace Vendor\Module\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()
{
$height = $this->getRequest()->getParam('height');
$weight = $this->getRequest()->getParam('weight');
$result = $this->resultJsonFactory->create();
$resultPage = $this->resultPageFactory->create();
$block = $resultPage->getLayout()
->createBlock('Vendor\Module\Block\Index')
->setTemplate('Vendor_Module::result.phtml')
->setData('height',$height)
->setData('weight',$weight)
->toHtml();
$result->setData(['output' => $block]);
return $result;
}
}
Result Layout File -
Vendor/Module/view/frontend/layout/module_result_result.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>Result</title>
</head>
<body>
<referenceContainer name="content">
<block class="Vendor\Module\Block\Index" name="result_result" template="Vendor_Module::result.phtml" />
</referenceContainer>
</body>
</page>
Result PHTML file -
Vendor/Module/view/frontend/templates/result.phtml
<?php
echo $block->getHeightData();
echo $block->getWeightData();
?>
Best Answer
You can just set below code in your phtml file to use ajax, You have to change your customurl in below code,
inside your controller file execute() method,