Javascript функция регистрации - PullRequest
1 голос
/ 20 января 2020

Здесь я пытаюсь использовать функцию signUp(), чтобы получить сведения о пользователях и сохранить их в базе данных. Я уже проверил файл backend Javascript (функция signUp), используя почтальон, и он отлично работает.

HTML:

<!DOCTYPE html>
<html>

<head>
    <title>Login</title>

    <link href="css\signup.css" rel="stylesheet" type="text/css">

    <script>

        function signUp() {
            if (document.getElementById("password2").value == document.getElementById("cfmpassword2").value) {
                var users = new Object();
                users.firstName = document.getElementById("firstName").value;
                users.lastName = document.getElementById("lastName").value;
                users.username2 = document.getElementById("username2").value;
                users.email = document.getElementById("email").value;
                users.password2 = document.getElementById("password2").value;


                var postUser = new XMLHttpRequest(); // new HttpRequest instance to send user details

                postUser.open("POST", "/users", true); //Use the HTTP POST method to send data to server

                postUser.setRequestHeader("Content-Type", "application/json");

                // Convert the data in "users" object to JSON format before sending to the server.
                postUser.send(JSON.stringify(users));
            }
            else {
                alert("Password column and Confirm Password column doesn't match!")
            }
        }

    </script>


</head>

<body>

    <div style="margin-top: -703px; margin-left: 1250px; position: absolute;">
        <!-- Sign up button -->
        <p>Need an account? &nbsp;
            <button class="signup" id='signup' onclick="document.getElementById('id02').style.display='block'" style="width:auto; height: 6.1vh;">
                Sign Up
            </button>
        </p>
    </div>

    <!-- The Sign Up Modal-->
    <div id="id02" class="modal2">
        <span onclick="document.getElementById('id02').style.display='none'" class="close2" title="Close Modal">&times;</span>

        <!-- Modal Content -->
        <form class="modal-content2">
            <div class="container3">
                <h1>Sign Up</h1>
                <p>Please fill in this form to create an account.</p>
                <hr>
                <label for="firstName"><b>First Name</b></label>
                <input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>

                <label for="lastName"><b>Last Name</b></label>
                <input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>

                <label for="username"><b>Username</b></label>
                <input type="text" id="username2" placeholder="Enter Username" name="username" required>

                <label for="email"><b>Email</b></label>
                <input type="text" id="email" placeholder="Enter Email" name="email" required>

                <label for="psw"><b>Password</b></label>
                <input type="password" id="password2" placeholder="Enter Password" name="psw" required>

                <label for="psw-confirm"><b>Confirm Password</b></label>
                <input type="password" id="cfmpassword2" placeholder="Confirm Password" name="psw-confirm" required>

                <br>
                <br>
                <p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms &
                        Privacy</a>.</p>

                <div class="clearfix">
                    <button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
                    <button type="submit" class="signupbtn" onclick="signUp()">Sign Up</button>
                </div>
            </div>
        </form>
    </div>

</body>

</html>

Если Confirm Password соответствует Password, я получу данные пользователя и отправлю данные на сервер базы данных. В противном случае должно появиться предупреждающее сообщение.

Однако, попробовав его, я не вижу ничего добавляемого в мою базу данных. Моя часть else работает, но в моем браузере появляется предупреждение.

Это из-за ошибки в Confirm Password? Потому что у меня очень похожий набор рабочих кодов, за исключением того, что он не содержит столбец Confirm Password. Отсюда я получил пароль подтверждения как проверить поле подтверждения пароля в форме без перезагрузки страницы

Может кто-нибудь помочь определить проблему? Большое спасибо!

Ответы [ 2 ]

0 голосов
/ 20 января 2020

Ваш комментарий о том, что замена submit на обычный button лишает вас возможности фактически нажимать, кажется немного странным. Приведенный ниже код имеет стандартную кнопку и выглядит нормально, что, возможно, указывает на проблему css. Я проверил это с помощью конечной точки php, и запрос был отправлен в порядке, так что он должен быть найден при попадании в конечную точку javascript - если только не существует другого фактора (css вероятнее всего), который мешает кнопке

<!DOCTYPE html>
<html>

<head>
    <title>Login</title>
    <link href="css/signup.css" rel="stylesheet" type="text/css">
    <script>
        function signUp(event) {

            event.preventDefault();

            if (document.getElementById("password2").value == document.getElementById("cfmpassword2").value) {
                var users = new Object();
                    users.firstName = document.getElementById("firstName").value;
                    users.lastName = document.getElementById("lastName").value;
                    users.username2 = document.getElementById("username2").value;
                    users.email = document.getElementById("email").value;
                    users.password2 = document.getElementById("password2").value;


                var postUser = new XMLHttpRequest();
                    /* 
                        Optional:
                        A callback to process response from the server and possibly manipulate the DOM
                        or let the user know if things went OK.
                    */
                    postUser.onreadystatechange=function(){
                        if( this.status==200 && this.readyState==4 ){
                            alert( this.response )
                        }
                    }
                    postUser.open( "POST", "/users", true );
                    postUser.setRequestHeader( "Content-Type", "application/json" );
                    postUser.send( JSON.stringify( users ) );
            }
            else {
                alert("Password column and Confirm Password column doesn't match!")
            }
        }
    </script>
</head>
<body>

    <div style="margin-top: -703px; margin-left: 1250px; position: absolute;">
        <!-- Sign up button -->
        <p>Need an account? &nbsp;
            <button class="signup" id='signup' onclick="document.getElementById('id02').style.display='block'" style="width:auto; height: 6.1vh;">
                Sign Up
            </button>
        </p>
    </div>

    <!-- The Sign Up Modal-->
    <div id="id02" class="modal2">
        <span onclick="document.getElementById('id02').style.display='none'" class="close2" title="Close Modal">&times;</span>

        <!-- Modal Content -->
        <form class="modal-content2">
            <div class="container3">
                <h1>Sign Up</h1>
                <p>Please fill in this form to create an account.</p>
                <hr>
                <label for="firstName"><b>First Name</b></label>
                <input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>

                <label for="lastName"><b>Last Name</b></label>
                <input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>

                <label for="username"><b>Username</b></label>
                <input type="text" id="username2" placeholder="Enter Username" name="username" required>

                <label for="email"><b>Email</b></label>
                <input type="text" id="email" placeholder="Enter Email" name="email" required>

                <label for="psw"><b>Password</b></label>
                <input type="password" id="password2" placeholder="Enter Password" name="psw" required>

                <label for="psw-confirm"><b>Confirm Password</b></label>
                <input type="password" id="cfmpassword2" placeholder="Confirm Password" name="psw-confirm" required>

                <br>
                <br>

                <p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms & Privacy</a>.</p>

                <div class="clearfix">
                    <button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
                    <!--
                        modify the button to a standard button rather than a submit
                        - this enables the ajax function to do what is intended.

                        An alternative would be to invoke `event.preventDefault()` within
                        the signUp(event) function to stop the submit button from actually
                        submitting the form
                    -->
                    <button type="button" class="signupbtn" onclick="signUp(event)">Sign Up</button>
                </div>

            </div>
        </form>
    </div>

</body>

</html>
0 голосов
/ 20 января 2020

Вы звоните signUp(), когда нажата кнопка Отправить .

JavaScript выполняется, но по мере подготовки запроса XHR форма отправляется, браузер перемещается, и запрос XHR отменяется.

Не использовать кнопку отправки если вы не отправляете форму.

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