TransWikia.com

Magento 2: Insert Form data Using AJAX Request

Magento Asked on October 2, 2021

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 MagMCFControllerIndex;

use MagMCFModelMcfFactory;

class Save extends MagentoFrameworkAppActionAction
{
    protected $_mcfFactory;

    private $logger;

    public function __construct(
        MagentoFrameworkAppActionContext $context,
        McfFactory $mcfFactory
        // PsrLogLoggerInterface $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();

    }
}

3 Answers

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>

MagMCFviewfrontend

requirejs-config.js

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

MagMCFviewfrontendwebjs

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 MagMCFControllerIndex;

use MagMCFModelMcfFactory;

class Save extends MagentoFrameworkAppActionAction
{
    protected $_mcfFactory;
    private $logger;

    public function __construct(
        MagentoFrameworkAppActionContext $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.

Correct answer by Msquare on October 2, 2021

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.

Answered by Mohit Patel on October 2, 2021

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 MagentoFrameworkControllerResultFactory;
 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;
    } 

Answered by Hamendra Sunthwal on October 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP