JS Ajax Asyn c / Ожидание - Форма не отправлена - PullRequest
0 голосов
/ 13 января 2020

У меня проблемы с моим От. По какой-то причине, когда я отправляю форму, электронное письмо не сохраняется в базе данных.

Мой html / js делает два вызова Asyn c - Ожидание Ajax. Первая предоставляет пользователю inte rnet доступ (Hotspot), а 2cnd сохраняет электронную почту в базе данных. Маршрутизатор (Hotspot) находится в другой сети, чем сервер.

Обратите внимание, что работает 1-й xhr (пользователь получает доступ inte rnet), форма 2cnd сообщает XHR2 4 и XHR2 200, но адрес электронной почты не сохраняется в базе данных.

Я (в настоящее время) использую XAMPP, если это относится к делу. Я также добавил ServerName 10.30.20.30:80 в файл httpd.config.

Если я могу предоставить какую-либо дополнительную информацию, дайте мне знать.

Любая помощь в решении этой проблемы будет принята с благодарностью.

Спасибо

HTML

<!DOCTYPE html>
<html>
<head>
<meta content="text/html" />
<meta charset="utf-8" />

<title>HotSpot</title>

</head>
<body>

    <!-- Form za mail, ki se spravi v DB -->
    <form accept-charset="utf-8" name="mail" onsubmit="return false;" method="post" id="mail">
        <h1>Hotspot</h1>
        <h2>To gain internet access, enter your email.</h2>
        <br />
        <input type="text" id="email" name="email" autofocus="autofocus" />
        <br />
        <input type="button" value="Submit" id="submit_ok" name="submit_ok" /> <br />
    </form>

<script type="text/javascript">

document.getElementById("submit_ok").addEventListener("click", sendAjax);

async function sendAjax() {
    let ax1 = await Ajax1 ("POST", "http://10.5.50.1/login")
    let ax2 = await Ajax2 ("POST", "http://10.30.20.30/Site/anti-xss.php")
}

function Ajax1 (method, url){
    return new Promise (function (resolve,  reject){
        let xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://10.5.50.1/login', true);
        xhr.onload = function(){
            if(this.status >= 200 && this.status < 300){
                resolve(xhr.response);
                console.log("Success!");
                console.log("You'r logged in.");
                console.log("XHR1 " + xhr.readyState);
                console.log("XHR1 " + xhr.status);
            }else{
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            }
        };
        xhr.onerror = function (){
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        };
        xhr.send("username=HSuser&password=SimpleUserPassword");
    });
}

function Ajax2 (method, url){
    return new Promise (function (resolve, reject){
        let xhr2 = new XMLHttpRequest();
        xhr2.open('POST', 'http://10.30.20.30/Site/anti-xss.php', true);
        xhr2.onload = function(){
            if(this.status >= 200 && this.status < 300){
                resolve(xhr2.response);
                console.log("Success!");
                console.log("You'r email is " + useremail + ".");
                console.log("XHR2 " + xhr2.readyState);
                console.log("XHR2 " + xhr2.status);
            }else{
                reject({
                    status: this.status,
                    statusText: xhr2.statusText
                });
            }
        };
        xhr2.onerror = function (){
            reject({
                status: this.status,
                statusText: this.statusText
            });
        };
        let useremail = document.getElementById("email").value;                 
        xhr2.send("Email="+encodeURIComponent(useremail));
    });
}

</script>   
</body>
</html>

PHP

<?php

    require ('connect.php');

    $clean_email = "";
    $cleaner_email = "";


    if(isset($_POST['Email']) && !empty($_POST['Email'])){
        //sanitize with filter
        $clean_email = filter_var($_POST['Email'], FILTER_SANITIZE_EMAIL);
        //sanitize with test_input
        $cleaner_email = test_input($clean_email);
        //validate with filter
        if (filter_var($cleaner_email,FILTER_VALIDATE_EMAIL)){
            // email is valid and ready for use
            echo "Email is valid";  
            //Email is a column in the Database
            $stmt = $DB->prepare("INSERT INTO naslovi (Email) VALUES (?)");
            $stmt->bind_param("s", $cleaner_email);
            $stmt->execute();
            $stmt->close();
        } else {
            // email is invalid and should be rejected
            echo "Invalid email, try again";
        } 
    } else {
    echo "Please enter an email";
    }

    function test_input($data) {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
    }

    $DB->close();   
?>

1 Ответ

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

После добавления getRequestHeader к XHR2 и добавления полсекунды задержки между вызовом XHR1 и вызовом XHR2 все, кажется, работает.

Спасибо @ADyson, вы помогли, было неоценимо =)

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