mrzaizai2233 / magento2-dev-log

0 stars 0 forks source link

How to validate form #2

Open mrzaizai2233 opened 6 years ago

mrzaizai2233 commented 6 years ago
<script type="text/javascript">
    require([
        'jquery',
        'mage/mage',
    ], function($){

        var dataForm = $('#cart-form');
        dataForm.mage('validation', {});

    });
</script>
mrzaizai2233 commented 6 years ago

https://magento.stackexchange.com/questions/158541/magento-2-how-to-send-data-using-ajax-form-in-custom-form Accepted answer is good, but i think could be useful take advantage of the js validation that magento core offers. So, try to use below js script:

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

Don't forget that controller has to return JSON response like:

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

return $response;