Magento 2 – How to Send Data Using Ajax in Custom Form

ajaxmagento2

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.

Best Answer

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) {             
                country = response.responseJSON.default_country;
                state = response.responseJSON.state;         
                console.log(state+' '+country);   
                },
                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');
        $country = 'india';
        $state = 'gujarat';
        $response->setContents(
            $this->_jsonHelper->jsonEncode(
                [
                    'default_country' => $country,
                    'state' => $state,
                ]
            )
        );
        return $response;
    } 
Related Topic