Отправьте данные формы без javascript - PullRequest
0 голосов
/ 08 апреля 2020

TL; DR

Как сделать форму, чтобы сделать нормальное сообщение вместо отправки через JQuery?


Я купил Тема недавно и я делаю форму с несколькими шагами. Я использую компонент «Мастер» этой темы, и вы можете увидеть, как он работает по этой ссылке:

https://keenthemes.com/metronic/preview/demo1/custom/pages/wizard/wizard-2.html

Моя проблема с представлением этой формы. Я хотел бы сделать общее представление. В настоящее время форма должна быть отправлена ​​с использованием JQuery.

Я внес некоторые изменения в свою форму, чтобы иметь возможность сделать общее представление. Например:

Я сообщил метод POST и действие для формы:

<form class="m-form m-form--label-align-right- m-form--state-" id="m_form" action="sale/new" method="post" enctype="multipart/form-data">

И я также создал кнопку «Отправить»:

<button type="submit" class="btn btn-primary" data-wizard-action="submit">Save</button>

Для Работа мастера, форма должна иметь идентификатор (m_form), а кнопка отправки также должна иметь атрибут data-wizard-action = "submit".

Я использую javascript самой темы, и именно потому, что я не знаю много о JS, я считаю, что столкнулся с проблемами. Я попытался удалить e.preventDefault, но форма все еще не POST к определенному мною действию. Код javascript для темы, которую я использую, таков:

//== Class definition
var WizardDemo = function () {
    //== Base elements
    var wizardEl = $('#m_wizard');
    var formEl = $('#m_form');
    var validator;
    var wizard;

    //== Private functions
    var initWizard = function () {
        //== Initialize form wizard
        wizard = new mWizard('m_wizard', {
            startStep: 1
        });

        //== Validation before going to next page
        wizard.on('beforeNext', function(wizardObj) {
            if (validator.form() !== true) {
                wizardObj.stop();  // don't go to the next step
            }
        })

        //== Change event
        wizard.on('change', function(wizard) {
            mUtil.scrollTop();            
        });

        //== Change event
        wizard.on('change', function(wizard) {
            if (wizard.getStep() === 1) {
                // alert(1);
            }           
        });
    }

    var initValidation = function() {
        validator = formEl.validate({
            //== Validate only visible fields
            ignore: ":hidden",

            //== Validation rules
            rules: {
                //=== Client Information(step 1)
                //== Client details
                name: {
                    required: true 
                },
                email: {
                    required: true,
                    email: true 
                },       
                phone: {
                    required: true,
                    phoneUS: true 
                },     

                //== Mailing address
                address1: {
                    required: true 
                },
                city: {
                    required: true 
                },
                state: {
                    required: true 
                },
                city: {
                    required: true 
                },
                country: {
                    required: true 
                },

                //=== Client Information(step 2)
                //== Account Details
                account_url: {
                    required: true,
                    url: true
                },
                account_username: {
                    required: true,
                    minlength: 4
                },
                account_password: {
                    required: true,
                    minlength: 6
                },                

                //== Client Settings
                account_group: {
                     required: true
                },                
                'account_communication[]': {
                    required: true
                },

                //=== Client Information(step 3)
                //== Billing Information
                billing_card_name: {
                    required: true
                },
                billing_card_number: {
                    required: true,
                    creditcard: true
                },
                billing_card_exp_month: {
                    required: true
                },
                billing_card_exp_year: {
                    required: true
                },
                billing_card_cvv: {
                    required: true,
                    minlength: 2,
                    maxlength: 3
                },

                //== Billing Address
                billing_address_1: {
                    required: true
                },
                billing_address_2: {

                },
                billing_city: {
                    required: true
                },
                billing_state: {
                    required: true
                },
                billing_zip: {
                    required: true,
                    number: true
                },
                billing_delivery: {
                    required: true
                },

                //=== Confirmation(step 4)
                accept: {
                    required: true
                }
            },

            //== Validation messages
            messages: {
                'account_communication[]': {
                    required: 'You must select at least one communication option'
                },
                accept: {
                    required: "You must accept the Terms and Conditions agreement!"
                } 
            },

            //== Display error  
            invalidHandler: function(event, validator) {     
                mUtil.scrollTop();

                swal({
                    "title": "", 
                    "text": "There are some errors in your submission. Please correct them.", 
                    "type": "error",
                    "confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
                });
            },

            //== Submit valid form
            submitHandler: function (form) {

            }
        });   
    }

    var initSubmit = function() {
        var btn = formEl.find('[data-wizard-action="submit"]');

        btn.on('click', function(e) {
            e.preventDefault();

            if (validator.form()) {
                //== See: src\js\framework\base\app.js
                mApp.progress(btn);
                //mApp.block(formEl); 

                //== See: http://malsup.com/jquery/form/#ajaxSubmit
                formEl.ajaxSubmit({
                    success: function() {
                        mApp.unprogress(btn);
                        //mApp.unblock(formEl);

                        swal({
                            "title": "", 
                            "text": "The application has been successfully submitted!", 
                            "type": "success",
                            "confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
                        });
                    }
                });
            }
        });
    }

    return {
        // public functions
        init: function() {
            wizardEl = $('#m_wizard');
            formEl = $('#m_form');

            initWizard(); 
            initValidation();
            initSubmit();
        }
    };
}();

jQuery(document).ready(function() {    
    WizardDemo.init();
});

Я хотел бы знать, есть ли способ сохранить мастер и проверку работоспособности, но таким образом, чтобы можно сделать общее представление для действия, которое я определил для формы.

1 Ответ

0 голосов
/ 08 апреля 2020

Вам просто нужно немного изменить функцию initSubmit () .

var initSubmit = function() {
    var btn = formEl.find('[data-wizard-action="submit"]');

    btn.on('click', function(e) {
        e.preventDefault();

        if (validator.form()) {
            //== See: src\js\framework\base\app.js
            mApp.progress(btn);
            //mApp.block(formEl); 

            //== See: http://malsup.com/jquery/form/#ajaxSubmit
            /*
            formEl.ajaxSubmit({
                success: function() {
                    mApp.unprogress(btn);
                    //mApp.unblock(formEl);

                    swal({
                        "title": "", 
                        "text": "The application has been successfully submitted!", 
                        "type": "success",
                        "confirmButtonClass": "btn btn-secondary m-btn m-btn--wide"
                    });
                }
            });
            */

            // Use this one instead:
            formEl.submit();
        }
    });
}

Это просто означает, что: вместо выполнения запроса AJAX, если результат проверки положительный, просто сделайте обычное представление.

Вот ссылка для метода submit () jQuery: https://api.jquery.com/submit/

Кстати, этот вопрос можно найти под заголовком (как отправить форму, используя jQuery?), См. Этот вопрос, например: Отправьте форму, используя jQuery

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...