Magento 2: Как отправлять данные с помощью Ajax-формы в пользовательской форме?


Кто-нибудь может объяснить мне, как я могу создать простую форму на странице Magento-2 для отправки данных с помощью Ajax? У меня уже есть форма и действие контроллера, которые отправляют данные без использования ajax.

Author: BornCoder, 2017-02-07

2 answers

Вы можете просто указать ниже код в своем файле phtml для использования ajax, Вы должны изменить свой пользовательский адрес в приведенном ниже коде,

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

Внутри файла контроллера выполнить() метод,

<?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;
    } 
 17
Author: Rakesh Jesadiya, 2017-02-07 12:39:35

Принятый ответ хорош, но я думаю, что было бы полезно воспользоваться проверкой js, которую предлагает ядро magento. Итак, попробуйте использовать приведенный ниже js-скрипт:

<script type="text/javascript">
require([
    "jquery",
    "mage/mage"
],function($) {
    $(document).ready(function() {
        $('#form_id').mage(
            'validation',
            { 
                submitHandler: function(form) {
                    $.ajax({
                        url: "url to module/controller/action",
                        data: $('#form_id').serialize(),
                        type: 'POST',
                        dataType: 'json',
                        beforeSend: function() {
                            // show some loading icon
                        },
                        success: function(data, status, xhr) {
                            // data contains your controller response
                        },
                        error: function (xhr, status, errorThrown) {
                            console.log('Error happens. Try again.');
                            console.log(errorThrown);
                        }
                    });
                }
            }
        );
    });
});
</script>

Не забывайте, что контроллер должен возвращать ответ JSON, например:

$response = $this->resultFactory
    ->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
    ->setData([
        'status'  => "ok",
        'message' => "form submitted correctly"
    ]);

return $response;
 16
Author: LucScu, 2018-02-06 08:00:00