at the first I consider both if and else block executed. After added debugger to code, I don't know why my code run more than once.
function Submit(form) {
var timer_starttime = document.getElementById("timer_starttime");
var timer_finishtime = document.getElementById("timer_finishtime");
if (wait_s.reportValidity() && wait_m.reportValidity()) {
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_program";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
document.getElementById("success-alert").className = "alert alert-success alert-dismissible";
console.log(this.responseText);
console.log("if");
debugger;
} else {
document.getElementById("error-alert").className = "alert alert-danger alert-dismissible";
console.log("else");
}
};
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({
"timer_finishtime": timer_finishtime.value,
"timer_starttime": timer_starttime.value
}));
}
return false;
}
console.log("end");
<form id="TimeForm" action="" method="POST">
...
<button type="submit" onclick="return Submit(this);">Save</button>
CodePudding user response:
When you send an AJAX request, the request goes through a number of states. See the documentation of XMLHttpRequest.readyState
for the full details.
The onreadystatechange
function will be called each time the state changes. So your else
block will be executed repeatedly for all the initial states. Then when the request completes successfully, the if
block will be executed.
You should only check for an error in the final state 4
, not treat all the other states as errors.
function Submit(form) {
var timer_starttime = document.getElementById("timer_starttime");
var timer_finishtime = document.getElementById("timer_finishtime");
if (wait_s.reportValidity() && wait_m.reportValidity()) {
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "/submit_program";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
//document.getElementById("ajax_res").innerHTML = this.responseText;
document.getElementById("success-alert").className = "alert alert-success alert-dismissible";
console.log(this.responseText);
console.log("if");
debugger;
} else {
document.getElementById("error-alert").className = "alert alert-danger alert-dismissible";
console.log("else");
}
}
};
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({
"timer_finishtime": timer_finishtime.value,
"timer_starttime": timer_starttime.value
}));
}
return false;
}
console.log("end");
<form id="TimeForm" action="" method="POST">
...
<button type="submit" onclick="return Submit(this);">Save</button>