1

I have an ajax form I need to call before allowing user to continue to add a product to cart. I have the form popping up but I also need to validate the contents before it submits. However the validation has changed from M1 to M2.

Essentially I need to:

  • on form submit
  • validate the form
  • if validate then submit AJAX request
  • if not valid then show validation errors.

How do I catch the form submit after the validation has happened? As if I use a regular JS event then the validation hasn't happened yet

Hope that makes sense.

  • As an alternative, you could validate the form components individually using 'change' event handlers and disable submit button until everything passes validation. – Aaron Allen Jul 13 '16 at 18:00
5

Use below code for submit and validate form using ajax

require([
    'jquery',
    'mage/mage',
    'Magento_Catalog/product/view/validation',
    'Magento_Catalog/js/catalog-add-to-cart'

], function ($) {
    'use strict';

    $('#custom_addtocart_form').mage('validation', {
        radioCheckboxClosest: '.nested',
        submitHandler: function (form) {
            jQuery.ajax({
                url: form.action,
                type: 'POST',
                dataType: 'json',
                data: form.serialize(),
                showLoader: true
            }).done(function (data) {
                return true;
            });

        }
    });


});

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.