I have a sign up form and I have a javascript function while validates the form input with a fetch request to a php file. The code is as follows:
form.onsubmit = function() {
let signInData = JSON.stringify(Object.fromEntries(new FormData(form).entries()));
let flag = false;
fetch('php/sign_up.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: signInData,
})
.then(response => response.text())
.then(data => {
if(data != "1") {
document.getElementById("sign_up_error").innerHTML = data;
flag = false;
} else {
flag = true;
}
});
return flag
};
Now the fetch command requires some time to finish and the .onsubmit function returns a value before it completes. Now I know that an asynchronous function can be used to wait for the fetch to finish using async-await, but have a look. Let's visualize the code for the form:
if(form.onsubmit()) {
sendFormData();
}
As you can see, they don't use an asynchronous function on their side to get the data, they use a synchronous function. On their side, form.onsubmit() would evaluate to an empty promise. And an empty promise as a boolean is true, so it would always just send the data. And I cannot use callback since the value has to be returned in that function itself.
Well I just found the answer myself using e.preventDefault and flags:
let flag = false;
form.addEventListener("submit", formSubmit);
async function formSubmit(e) {
if(flag === true) {
return true;
} else {
e.preventDefault();
let signInData = JSON.stringify(Object.fromEntries(new FormData(form).entries()));
await fetch('php/sign_up.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: signInData,
})
.then(response => response.text())
.then(data => {
if(data != "1") {
document.getElementById("sign_up_error").innerHTML = data;
flag = false;
} else {
flag = true;
sign_up.submit();
}
});
}
};