0

I've been trying to get my AJAX POSTs to run sequentially. I've tried using onreadystatechange but I can't get it to work. So now I've decided to try Async / Await.

The problem is, that I don't fully understand how it works. I've read and re-read the documentation on Mozilla and I have browsed SO, but I can't seem to find a similar enough example which would help me.

So, basically what I would like to do, is:

user inputs his email and clicks submit,

1.) AJAX POST is made to the router with username and password which gives the user internet access.

after this is done, and we get readyState 4 and Status 200,

2.) another AJAX POST is made, to a web server which saves the users email to the database (router and the server are on a different network, that's why the user needs internet connection first)

after this is done, and we get readyState 4 and Status 200

3.) the user gets redirected.

I have tried moving open() and setRequestHeader() around but it didn't help.

Here is the complete HTML/JS code:

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

<title>HotSpot</title>

</head>
<body>

    <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);

    function SendAjax() {
        var email = document.getElementById("email").value;
        console.log(email);
        // Check if fields are empty 
        if (email=="") {
            alert("Please enter your email.");
        }
        // AJAX code to submit form
        else{
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                var DONE = 4;
                var OK = 200;

                if (xhr.readyState === DONE){
                    if (xhr.status === OK){
                        var xhr2 = new XMLHttpRequest();
                        xhr2.onreadystatechange = function () {
                            if (xhr.readyState === DONE){
                                if (xhr.status === OK){     
                                    location.href = "http://server/redirected.html";
                                }
                            }
                        }
                    }
                    xhr2.open('POST', 'http://server/insertDB.php', true);
                    xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
                    var useremail = document.getElementById("email").value;
                    xhr2.send("Email="+encodeURIComponent(useremail));
                }
            }
        xhr.open('POST', 'http://router/login', true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
        xhr.send("popup=true&username=HSuser&password=SimpleUserPassword");
        }
    };

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

I think the Async/Await code should looks something like this, but as stated before, I'm really not sure what to do.

Right of the bat, I get sendAjax is not defined.

(async function sendAJAX(){
    const ax1 = await Ajax1()
    const ax2 = await Ajax2()
    const ax3 = await Ajax3()
})

function Ajax1(){
    let xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://router/login', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
    xhr.send("popup=true&username=HSuser&password=SimpleUserPassword");
}

function Ajax2(){
    let xhr2 =  new XMLHttpRequest();
    xhr2.open('POST', 'http://server/insertDB.php', true);
    xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
    var useremail = document.getElementById("email").value;
    xhr2.send("Email="+encodeURIComponent(useremail));  
}

function Ajax3(){
    location.href = "http://server/redirected.html";
}
DrDoom
  • 325
  • 1
  • 2
  • 12
  • 2
    you should definitely use `fetch()` – Nico Jan 09 '20 at 14:51
  • I've also checked out https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch but I just get confused. Should I write xhr in a different way if I'm using fetch? – DrDoom Jan 09 '20 at 14:57

0 Answers0