Как добавить мой серверный PHP-код в этот мастер форм?

Я разработал простой мастер 3-х шаговой формы для регистрации.

Вся проверка на стороне клиента (JavaScript) работает.

Проблема в том, что когда пользователь доходит до последнего этапа и нажимает «Отправить», он ничего не делает.

Я хочу, чтобы он указывал на написанный мной PHP-код.

Обновлять Следующая кнопка ничего не делает, когда я нажимаю на нее после обновления моего html-кода

Обновленный HTML-код

<form action = "register.php">
    <div id  = "personal-form">
        <h4><b>Personal Details:</b></h4>
        <hr>
        <div class = "form-group">
            <label class = "sr-only" for = "first-name">First name</label>
            First Name
            <input type = "text" name = "firstname" placeholder = "" class = "form-control" id = "firstname">
        </div>
        <div class = "form-group">
            Last Name
            <label class = "sr-only" for = "last-name">Last name</label>
            <input type = "text" name = "lastname" placeholder = "" class = "form-control" id = "lastname">
        </div>
        <div class = "form-group">
            Phone Number
            <label class = "sr-only" for = "name">Phone Number</label>
            <input type = "text" name = "phone" placeholder = "" class = "form-control" id = "phone">
        </div>
        <div class = "form-group">
            <p class = "has-error" id = "error-msg"></p>
        </div>
        <div class = "f1-buttons">
            <button type = "button" id = "first-next" class = "btn btn-next">Next</button>
        </div>
</div>

    <div id = "store-form">
    ........

    <button type = "button" class = "btn btn-previous" id = "first- 
    previous">Previous</button>
    <button type = "button" class = "btn btn-next" 
    id = "second-next">Next</button></center>                 
    </div>

    <div id = "account-form">

    ........

    <button type = "button" class = "btn btn-previous" id = "second- 
    previous">Previous</button>
    <button type = "submit" class = "btn btn-next" id = "submit">Submit</button> 
    </center>
    </div>

   </form>

Код JavaScript

function init() {
    //hide the other two forms
    $("#store-form").hide();
    $("#account-form").hide();

    //$("#first-next").addClass("disabled");

    //var state2 = $("#state").val();

    /*$("#state").change(function ()
    {
        var state2 = $("#state").val();
        alert(state2);
    })*/

    //alert(state2);

    $.validator.setDefaults({
        errorClass: 'help-block',
        highlight: function (element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error');
        }
    })

    $.validator.addMethod('strongPassword', function (value, element) {
        return this.optional(element) || value.length >= 6
        // && /\d/.test(value) && /[a-z]/i.test(value);
    }, 'Your password must be at least 6 characters long');//'Your password must be at least 6 characters long, contain at least on e number and a character');

    //The method for all select options
    $.validator.addMethod('checkSelect', function (value, element) {
        return this.optional(element) || (value != "Please choose...")
        // && /\d/.test(value) && /[a-z]/i.test(value);
    }, 'You must select an option');//'Your password must be at least 6 characters long, contain at least on e number and a character');

    $("#personal-form").validate({
        rules: {
            firstname: {
                required: true,
                nowhitespace: true,
                lettersonly: true
            },
            lastname: {
                required: true,
                nowhitespace: true,
                lettersonly: true
            },
            phone: {
                required: true,
            }
        },
        messages: {
            firstname: {
                required: 'Please enter your first name',
                nowhitespace: 'Please enter a valid first name',
                lettersonly: 'Please enter only alphabets'
            },
            lastname: {
                required: 'Please enter your first name',
                nowhitespace: 'Please enter a valid last name',
                lettersonly: 'Please enter only alphabets'
            },
            phone: {
                required: "Please enter a valid phone no"
            }
        }
    });

    /*if ($("#personal-form").valid() == true)
    {
        $("#first-next").removeClass("disabled");
        alert($("#personal-form").valid());
    }*/

    if ($("#first-next").click(function () {
        if ($("#personal-form").valid() == true) {
        //$("#first-next").removeClass("disabled");
        //alert($("#personal-form").valid());

            $("#personal-form").hide();
            $("#store-form").fadeIn();
            $("#account-form").hide();

        //$("#error-msg").html("");
    }
    else {
        //$("#error-msg").html("Please correct all errors before clicking next");
    }
    }));

    /*$("#firstname").on('change', function() {
        if ($("#firstname").valid() == true)
        {
            console.info("test");
            alert("It worked");
        }
    });*/

    //$('#firstname').on('input', function()
    //{
    //var firstname = $("#firstname").val();
    //alert(firstname);
    //alert("hello");
    //console.info("test");
    //alert("You just typed something in the firstname field");
    //});

    $("#store-form").validate({
        rules: {
            storename: {
                required: true
            },
            state: {
                required: true,
                checkSelect: true
            },
            lga: {
                required: true,
                checkSelect: true
            },
            address: {
                required: true,
            },
            category: {
                required: true,
                checkSelect: true
            },
            description: {
                required: true,
                lettersonly: true
            }
        },
        messages: {
            storename: {
                required: "Please enter the name of your store"
            },
            address: {
                required: "Please enter the address of your store"
            },
            description: {
                required: "Briefly descibe what you sell or do"
            }
        }
    });

    if ($("#second-next").click(function () {
        if ($("#store-form").valid() == true) {
        //$("#first-next").removeClass("disabled");
        //alert($("#personal-form").valid());

            $("#personal-form").hide();
            $("#store-form").hide();
            $("#account-form").fadeIn();

        //$("#error-msg").html("");
    }
    else {
        //$("#error-msg").html("Please correct all errors before clicking next");
    }
    }));

    if ($("#first-previous").click(function () {
        $("#personal-form").fadeIn();
        $("#store-form").hide();
        $("#account-form").hide();

        //$("#error-msg").html("");
    }));

    $("#account-form").validate({
        rules: {
            email: {
                required: true,
                email: true
            },
            password: {
                required: true,
                strongPassword: true
            },
            password2: {
                required: true,
                equalTo: "#password"
            }
        },
        messages: {
            email: {
                required: 'Please enter your email address',
                email: "Please enter a valid email address"
            },
            password: {
                required: 'Please enter your password',
                strongPassword: "Your password is not strong enough"
            },
            password2: {
                required: 'Please enter your password',
                equalTo: "Both passwords don't match"
            }
        }
    });

    $("#email").on('input', function () {
        if ($("#email").valid() == true) {
            //console.info("test");
            //alert("It worked");

            var email = $("#email").val();

            $("#check-email-server").load('php/check_email.php', { "email": email });
        }
    });

    $("#email").on('focusout', function () {
        if ($("#email").valid() == true) {
            //console.info("test");
            //alert("It worked");

            var email = $("#email").val();

            $("#check-email-server").load('php/check_email.php', { "email": email });
        }
    });

    if ($("#second-previous").click(function () {
        $("#personal-form").hide();
        $("#store-form").fadeIn();
        $("#account-form").hide();

        //$("#error-msg").html("");
    }));
}

Все три формы должны подключаться к 1 файлу PHP.

Проблема в том, что когда я нажимаю «Отправить», ничего не происходит.

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

Как добавить мой серверный PHP-код в этот мастер форм?

Как добавить мой серверный PHP-код в этот мастер форм?

Как добавить мой серверный PHP-код в этот мастер форм?

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
162
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Последняя кнопка должна иметь тип «отправить» <button type = "submit">, иначе обычная «кнопка» не отправляет форму (или, может быть, вам нужно написать событие js click для отправки формы.)

А ТАКЖЕ

Вы должны поместить все входные данные в одну и ту же форму, чтобы отправить их на php, подумайте о замене форм на div и оберните их в уникальную форму. Если вы используете 3 разные формы, в бэкэнд будут отправлены только элементы ввода последней формы, но я думаю, вам нужны все входные данные.

Это пример: http://jsfiddle.net/2sdtjydu/1/

<form action = "" method = "post">
    <div id  = "personal-form">
        <h4><b>Personal Details:</b></h4>
        <hr>
        <div class = "form-group">
            <label class = "sr-only" for = "first-name">First name</label>
            First Name
            <input type = "text" name = "firstname" placeholder = "" class = "form-control" id = "firstname">
        </div>
        <div class = "form-group">
            Last Name
            <label class = "sr-only" for = "last-name">Last name</label>
            <input type = "text" name = "lastname" placeholder = "" class = "form-control" id = "lastname">
        </div>
        <div class = "form-group">
            Phone Number
            <label class = "sr-only" for = "name">Phone Number</label>
            <input type = "text" name = "phone" placeholder = "" class = "form-control" id = "phone">
        </div>
        <div class = "form-group">
            <p class = "has-error" id = "error-msg"></p>
        </div>
        <div class = "f1-buttons">
            <button type = "button" id = "first-next" class = "btn btn-next">Next</button>
        </div>
</div>

    <div id = "store-form">
    ........

    <button type = "button" class = "btn btn-previous" id = "first- 
    previous">Previous</button>
    <button type = "button" class = "btn btn-next" 
    id = "second-next">Next</button>           
    </div>

    <div id = "account-form">

    ........

    <button type = "button" class = "btn btn-previous" id = "second- 
    previous">Previous</button>
    <button type = "submit" class = "btn btn-next" id = "submit">Submit</button> 
    </div>

   </form>

И это jquery:

$(document).ready(function () {
  //hide the other two forms
    $("#store-form").hide();
    $("#account-form").hide();

    //$("#first-next").addClass("disabled");

    //var state2 = $("#state").val();

    /*$("#state").change(function ()
    {
        var state2 = $("#state").val();
        alert(state2);
    })*/

    //alert(state2);

    $.validator.setDefaults({
        errorClass: 'help-block',
        highlight: function (element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error');
        }
    })

    $.validator.addMethod('strongPassword', function (value, element) {
        return this.optional(element) || value.length >= 6
        // && /\d/.test(value) && /[a-z]/i.test(value);
    }, 'Your password must be at least 6 characters long');//'Your password must be at least 6 characters long, contain at least on e number and a character');

    //The method for all select options
    $.validator.addMethod('checkSelect', function (value, element) {
        return this.optional(element) || (value != "Please choose...")
        // && /\d/.test(value) && /[a-z]/i.test(value);
    }, 'You must select an option');//'Your password must be at least 6 characters long, contain at least on e number and a character');
$("form").validate({
        rules: {
            firstname: {
                required: true,
                nowhitespace: true,
                lettersonly: true
            },
            lastname: {
                required: true,
                nowhitespace: true,
                lettersonly: true
            },
            phone: {
                required: true,
            },
                    storename: {
                required: true
            },
            state: {
                required: true,
                checkSelect: true
            },
            lga: {
                required: true,
                checkSelect: true
            },
            address: {
                required: true,
            },
            category: {
                required: true,
                checkSelect: true
            },
            description: {
                required: true,
                lettersonly: true
            },
                        email: {
                required: true,
                email: true
            },
            password: {
                required: true,
                strongPassword: true
            },
            password2: {
                required: true,
                equalTo: "#password"
            }
        },
        messages: {
            firstname: {
                required: 'Please enter your first name',
                nowhitespace: 'Please enter a valid first name',
                lettersonly: 'Please enter only alphabets'
            },
            lastname: {
                required: 'Please enter your first name',
                nowhitespace: 'Please enter a valid last name',
                lettersonly: 'Please enter only alphabets'
            },
            phone: {
                required: "Please enter a valid phone no"
            },
            storename: {
                required: "Please enter the name of your store"
            },
            address: {
                required: "Please enter the address of your store"
            },
            description: {
                required: "Briefly descibe what you sell or do"
            },
            email: {
                required: 'Please enter your email address',
                email: "Please enter a valid email address"
            },
            password: {
                required: 'Please enter your password',
                strongPassword: "Your password is not strong enough"
            },
            password2: {
                required: 'Please enter your password',
                equalTo: "Both passwords don't match"
            }
        }
    });


    /*if ($("#personal-form").valid() == true)
    {
        $("#first-next").removeClass("disabled");
        alert($("#personal-form").valid());
    }*/

    if ($("#first-next").click(function () {
        if ($("#personal-form :input").valid() == true) {
        //$("#first-next").removeClass("disabled");
        //alert($("#personal-form").valid());

            $("#personal-form").hide();
            $("#store-form").fadeIn();
            $("#account-form").hide();

        //$("#error-msg").html("");
    }
    else {
        //$("#error-msg").html("Please correct all errors before clicking next");
    }
    }));

    /*$("#firstname").on('change', function() {
        if ($("#firstname").valid() == true)
        {
            console.info("test");
            alert("It worked");
        }
    });*/

    //$('#firstname').on('input', function()
    //{
    //var firstname = $("#firstname").val();
    //alert(firstname);
    //alert("hello");
    //console.info("test");
    //alert("You just typed something in the firstname field");
    //});


    if ($("#second-next").click(function () {
        if ($("#store-form :input").valid() == true) {
        //$("#first-next").removeClass("disabled");
        //alert($("#personal-form").valid());

            $("#personal-form").hide();
            $("#store-form").hide();
            $("#account-form").fadeIn();

        //$("#error-msg").html("");
    }
    else {
        //$("#error-msg").html("Please correct all errors before clicking next");
    }
    }));

    if ($("#first-previous").click(function () {
        $("#personal-form").fadeIn();
        $("#store-form").hide();
        $("#account-form").hide();

        //$("#error-msg").html("");
    }));

    $("#email").on('input', function () {
        if ($("#email").valid() == true) {
            //console.info("test");
            //alert("It worked");

            var email = $("#email").val();

            $("#check-email-server").load('php/check_email.php', { "email": email });
        }
    });

    $("#email").on('focusout', function () {
        if ($("#email").valid() == true) {
            //console.info("test");
            //alert("It worked");

            var email = $("#email").val();

            $("#check-email-server").load('php/check_email.php', { "email": email });
        }
    });

    if ($("#second-previous").click(function () {
        $("#personal-form").hide();
        $("#store-form").fadeIn();
        $("#account-form").hide();

        //$("#error-msg").html("");
    }));
});

Я сделал это, но кнопка NEXT теперь абсолютно ничего не делает. Проверьте мой обновленный html-код

Ibrahim 31.05.2018 20:46

Вы используете проверку на div, и вы должны использовать ее в форме. Где-то есть if ($ (..). Click ()), я не могу понять if по щелчку. Я отредактировал свой ответ, изменив ваш код, и создаю скрипку, чтобы лучше ее попробовать.

Tobia 31.05.2018 21:28

Ваш следующий код работает, но мне трудно реализовать его с моим кодом JS, чтобы проверка работала ... Я новичок в JS.

Ibrahim 01.06.2018 05:42

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

Tobia 01.06.2018 07:38

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

Ibrahim 02.06.2018 10:28

Попробуйте мою обновленную скрипку, я объединил проверку трех форм в одну

Tobia 02.06.2018 17:58

Другие вопросы по теме