简体   繁体   中英

JavaScript only works when alert() is called

I'm trying to send a POST request to a Java method that creates an account with the given form parameters in a database. If the account is successfully created the method returns true, and then I should get redirected to a link. But the code below doesn't work unless the alert("") function is there.

I assume it has something to do with asynchronous mode, but I'm new to JavasScript and would really appreciate any help :)

Here's the code:

function createAccount(){

var xhr = new XMLHttpRequest();

var fname = document.getElementById("fname").value;
var surname = document.getElementById("surname").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var rpassword = document.getElementById("rpassword").value;
var emp_no = document.getElementById("emp_no").value;

xhr.open('POST','http://localhost:8080/di24_app/di24/create',true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send('fname='+fname+'&surname='+surname+'&email='+email+'&password='+password+'&rpassword='+rpassword+'&emp_no='+emp_no);
xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
            document.getElementById("result").innerHTML = "Error creating account!";
            document.getElementById("result").style.textAlign = "center";
        }
        else if(this.responseText == "true"){
            window.location.href = "http://localhost:8080/di24_app/html/home_page/home.html";
        }
    }

}
alert("");
}

You can use callback methods inside your onreadystatechange function like below;

function createAccount(successCallback, errorCallback) {
   ...

   xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
           errorCallback();
        }
        else if(this.responseText == "true"){
           successCallback();
        }
    }
  }
}

Then you can call createAccount method with below two function params;

createAccount(
   function () { console.log('success') },
   function () { console.log('error') }
)

And you can write your dom manipulation codes into these callback functions.

The issue is that you have a button with type="submit" and onclick="createAccount()" is inside a <form/> , the browser will automatically post the data and refresh your page, after clicking that button, So the execution of the function createAccount() will never reach the end.

On the html button tag do this: <button type ="submit" onclick="return createAccount()">Create</button> add return before createAccount()

On the function createAccount() at the end add return false .

Returning a false when calling a method from a submit type button, will indicate to the browser to not automatically post form data.

function createAccount(){

....

xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
            document.getElementById("result").innerHTML = "Error creating account!";
            document.getElementById("result").style.textAlign = "center";
        }
        else if(this.responseText == "true"){
            window.location.href = "http://localhost:8080/di24_app/html/home_page/home.html";
        }
    }

}
//alert("");
return false; // important
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM