1

How to insert form data Using AJAX request.

This my phtml file

<html>

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>
    <div class="col-sm-8">
        <form method="POST" action="<?= $this->getUrl('mcf/index/save'); ?>" id="mcf" role="form" name="RegForm" enctype="multipart/form-data" data-mage-init='{"validation":{"rules": {"field-2": {"required":true}}}}'>
            <div class="form-group">
                <h2>Form</h2>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your Name') ?></span></label>
                <input id="name" name="name" type="text" class="form-control" data-validate='{"required":true}'>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your FirstName') ?></span></label>
                <input id="firstname" name="firstname" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your LastName') ?></span></label>
                <input id="lastname" name="lastname" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your  Address') ?></span></label>
                <input id="address" name="address" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label" for="field-2"><span><?= $block->escapeHtml('Your Mobile Number') ?></span></label>
                <input id="mo_number" name="mo_number" type="text" class="form-control" data-validate='{"required":true, "validate-number": true}'>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Gender') ?></span></label><br>
                <input type="radio" name="gender" value="male" checked>Male<br>
                <input type="radio" name="gender" value="female">FeMale<br>
                <input type="radio" name="gender" value="other">Other<br>
            </div>
            <div class="actions-toolbar">
                <div class="primary">
                    <button type="submit" title="Submit" class="action submit primary">
                        <span>Submit</span>
                    </button>
                </div>
            </div>
        </form>
    </div>
</body>

</html>
<style>
    .mcf-index-index .page-wrapper .panel.wrapper {
        display: none;
    }
</style>

This is my Controller file :-

<?php

namespace Mag\MCF\Controller\Index;

use Mag\MCF\Model\McfFactory;

class Save extends \Magento\Framework\App\Action\Action
{
    protected $_mcfFactory;

    private $logger;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        McfFactory $mcfFactory
        // \Psr\Log\LoggerInterface $logger
    ) {
        $this->_mcfFactory = $mcfFactory;
        parent::__construct($context);
        // $this->logger = $logger;
    }
    public function execute()
    {
        // echo "You are redirect Sucess";

        $post_data = (array) $this->getRequest()->getPost();
        $resultRedirect = $this->resultRedirectFactory->create();
        // echo "<pre>";
        // print_r($post_data);
        try {
            $Mcfdata = $this->_mcfFactory->create();
            $Mcfdata->setData($post_data);
            $Mcfdata->save();
            $this->messageManager->addSuccess(__("Save Data"));
            $resultRedirect->setPath('mcf/index/index/');
            return $resultRedirect;
        } catch (\Exception $e) {
            // $this->logger->critical($e->getMessage());
            $this->messageManager->addError(__('please try again. Form Not Submit'));
            $resultRedirect->setPath('mcf/index/index/');
            return $resultRedirect;
        }
        // exit();

    }
}
0

3 Answers 3

0

Try this code

phtml file

<html>

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body>
    <div class="col-sm-8">
        <form method="POST" action="<?= $this->getUrl('mcf/index/save'); ?>" id="mcf" role="form" name="RegForm" enctype="multipart/form-data" data-mage-init='{"validation":{"rules": {"field-2": {"required":true}}}}'>
            <div class="form-group">
                <h2>Form</h2>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your Name') ?></span></label>
                <input id="name" name="name" type="text" class="form-control" data-validate='{"required":true}'>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your FirstName') ?></span></label>
                <input id="firstname" name="firstname" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your LastName') ?></span></label>
                <input id="lastname" name="lastname" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Your  Address') ?></span></label>
                <input id="address" name="address" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label class="control-label" for="field-2"><span><?= $block->escapeHtml('Your Mobile Number') ?></span></label>
                <input id="mo_number" name="mo_number" type="text" class="form-control" data-validate='{"required":true, "validate-number": true}'>
            </div>
            <div class="form-group">
                <label class="control-label"><span><?= $block->escapeHtml('Gender') ?></span></label><br>
                <input type="radio" name="gender" value="male" checked>Male<br>
                <input type="radio" name="gender" value="female">FeMale<br>
                <input type="radio" name="gender" value="other">Other<br>
            </div>
            <div class="actions-toolbar">
                <div class="primary">
                    <button type="submit" title="Submit" id="mcf-btn" class="action submit primary" data-mage-init='{"mcf_js":{}}'>
                        <span>Submit</span>
                    </button>
                </div>
            </div>
        </form>
    </div>
</body>

</html>
<style>
    .mcf-index-index .page-wrapper .panel.wrapper {
        display: none;
    }
</style>

Mag\MCF\view\frontend

requirejs-config.js

var config = {
    map: {
        '*':{
                mcf_js:'Mag_MCF/js/mcf_js',
            }
        },
    shim:{
            'mcf_js':{
                                 deps: ['jquery']
                             }
        }
};

Mag\MCF\view\frontend\web\js

mcf_js.js

define(["jquery", "domReady!","mcf_js"], function($,dom,mcf_js){

    $(document).on('click', '#mcf-btn', function(e){
        var ajxurl = $('#mcf').attr('action');
        var formdata = new FormData(jQuery('#mcf')[0]);
        $.ajax({
            url: ajxurl,
            type: "POST",
            cache: false,
            contentType: false,
            processData: false,
            data: formdata,
            showLoader: true,
            success: function(data){
                location.reload();
                alert("Save");
            }
        });
        e.preventDefault();
    });

})

Your Controller file

<?php

namespace Mag\MCF\Controller\Index;

use Mag\MCF\Model\McfFactory;

class Save extends \Magento\Framework\App\Action\Action
{
    protected $_mcfFactory;
    private $logger;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        McfFactory $mcfFactory
    ) {
        $this->_mcfFactory = $mcfFactory;
        parent::__construct($context);
    }
    public function execute()
    {
        $post_data = $this->getRequest()->getPostValue();
        try {
            $Mcfdata = $this->_mcfFactory->create();
            $Mcfdata->setData($post_data);
            $Mcfdata->save();
            $this->messageManager->addSuccess(__("Save Data"));
        } catch (\Exception $e) {
            $this->messageManager->addError(__('please try again. Form Not Submit'));
        }
    }
}

I Hope This Helps You.

6
  • thanks. one question js code i have use in phtml file Jul 20, 2020 at 8:04
  • yes you can use this code into your phtml file also i have do this task using requirejs.
    – Msquare
    Jul 20, 2020 at 8:05
  • i have change your file please check and update me.
    – Msquare
    Jul 20, 2020 at 8:08
  • it possible you update answer?? Jul 20, 2020 at 8:08
  • above answer is works so we do not need to change.
    – Msquare
    Jul 20, 2020 at 8:08
2

You can just set below code in your phtml file to use ajax, You have to change your customurl in below code,

<script type="text/javascript">
    require(["jquery"],function($) {
        $(document).ready(function() {
            var customurl = "<?php echo $this->getUrl().'frontname/index/index'?>";
            $.ajax({
                url: customurl,
                type: 'POST',
                dataType: 'json',
                data: {
                    customdata1: 'test1',
                    customdata2: 'test2',
                },
            complete: function(response) {             
                version = response.responseJSON.version;
                magento = response.responseJSON.magento;         
                console.log(version+' '+magento);   
                },
                error: function (xhr, status, errorThrown) {
                    console.log('Error happens. Try again.');
                }
            });
        });
    });
</script>

inside your controller file execute() method,

<?php
 use Magento\Framework\Controller\ResultFactory;
 public function execute()
    {
        $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);

        $response = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $response->setHeader('Content-type', 'text/plain');
        $magento = 'magento';
        $version = 'version';
        $response->setContents(
            $this->_jsonHelper->jsonEncode(
                [
                    'version' => $version,
                    'magento' => $magento,
                ]
            )
        );
        return $response;
    } 
1

How to insert data using AJAX in magento 2 in .phtml file follow steps :-

First your .phtml file submit button add id like :-

<button type="submit" title="Submit" id="mcf-btn" class="action submit primary">
   <span>Submit</span>
</button>

After in .phtml file your require jQuery like :-

require(['jquery', 'jquery/ui'], function($) {
  //your AJAX code
});

And finally you add your ajax code like :-

$(document).on('click', '#mcf-btn', function(e) {
            var url = $('#mcf').attr('action');
            var formdata = new FormData(jQuery('#mcf')[0]);
            $.ajax({
                url: url,
                type: "POST",
                cache: false,
                contentType: false,
                processData: false,
                data: formdata,
                showLoader: true,
                success: function(data) {
                    location.reload();
                    alert("Save");
                }
            });
            e.preventDefault();
        });

And your controller code edit your execute() function :-

$post_data = (array) $this->getRequest()->getPost();
        $resultRedirect = $this->resultRedirectFactory->create();
        try {
            $Mcfdata = $this->_mcfFactory->create();
            $Mcfdata->setData($post_data);
            $Mcfdata->save();
            $this->messageManager->addSuccess(__("Save Data"));
        } catch (\Exception $e) {
            $this->messageManager->addError(__('please try again. Form Not Submit'));
        }

And after run some commands :-

php bin/magento c:c
php bin/magento c:f

THANKS.

1
  • you can not redirect code into ajax controller.
    – Msquare
    Jul 20, 2020 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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