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("");
}