On a event I’m checking a form to see if an email is used, I’ve put this in a function and want to reuse it when the form is submitted along with checking the username and other things.
I’m THINKING it’s because my code isn’t waiting for my fetch to return but I’m not sure if this is the case and if so how to solve it
Here’s my JS code
“`
function checkEmail(){
email.classList.remove(‘red’)
email.classList.remove(‘green’)
let formData = new FormData();
formData.append(’email’, email.value);
fetch(“../process/checkemail-available.php”,
{
body: formData,
method: “post”
})
.then(response => response.json())
.then(data => {
if (data.outcome == 0){
email.classList.add(‘green’)
return true;
} else {
email.classList.add(‘red’)
return false;
}
});
}
It works nicely on my focusout event.
On my submit event for my form I want to check if all conditions are true but what i have isn’t working why?
“`
if (checkUserName() == true || checkEmail() == true || checkLastname() == true){
console.log(‘Good to go!’)
}
>it's because my code isn't waiting for my fetch to return
then
```<i>
</i> function checkAll() {
const form = document.querySelectorAll('form');
if (form.dataset.statusEmail == 'ok'
&& form.dataset.statusLastName == 'ok'
&& form.dataset.statusUserName == 'ok') {
// All values are OK, submit form or transmit form data by ajax
form.submit();
}
}
function checkEmail(callback) {
email.classList.remove('red')
email.classList.remove('green')
let formData = new FormData();
formData.append('email', email.value);
fetch("../process/checkemail-available.php",
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == 0) {
email.classList.add('green');
// callback handed over? This is the case
// if the form was submitted.
if (callback) {
// note that email is OK:
document.querySelectorAll('form').dataset.statusEmail = 'ok';
// Now call callback in order to check
// if all values are OK and submit the form:
callback();
}
// return true;
} else {
email.classList.add('red')
// return false;
}
});
}
// Call all checking functions when the form is submitted:
checkUserName(checkAll);
checkEmail(checkAll);
checkLastname(checkAll);
// Submitting will be done when all responses from server have been received
// and all values are OK:<i>
</i>
`</CODE>
When checking a particular value, omit the callback and call the checking function without parameter.
Edit: You can use the class "green" as well in order to check if the value is OK. <C>
dataset.statusEmail
` etc. would be obsolete then.
document.querySelector('form').dataset.statusEmail = 'ok';
```<i>
</i>function checkAll() {
const form = document.querySelectorAll('form');
if (form.dataset.statusEmail == 'ok' && form.dataset.statusUsername == 'ok') {
// All values are OK, submit form or transmit form data by ajax
//form.submit();
console.log('submitform');
}
}
function checkEmail(callback) {
email.classList.remove('red')
email.classList.remove('green')
let formData = new FormData();
formData.append('email', email.value);
fetch("../process/checkemail-available.php",
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == 0) {
email.classList.add('green');
// callback handed over? This is the case
// if the form was submitted.
if (callback) {
// note that email is OK:
document.querySelector('form').dataset.statusEmail = 'ok';
// Now call callback in order to check
// if all values are OK and submit the form:
callback();
}
// return true;
} else {
email.classList.add('red')
// return false;
}
});
}
function checkUserName(callback) {
username.classList.remove('red')
username.classList.remove('green')
let formData = new FormData();
formData.append('username', username.value);
fetch("../process/checkusername-available.php",
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == 0) {
username.classList.add('green');
// callback handed over? This is the case
// if the form was submitted.
if (callback) {
// note that email is OK:
document.querySelector('form').dataset.statusUsername = 'ok';
// Now call callback in order to check
// if all values are OK and submit the form:
callback();
}
// return true;
} else {
username.classList.add('red')
// return false;
}
});
}<i>
</i>
``
const username = document.getElementById("username");
username.addEventListener('focusout', checkUserName);
const register = document.getElementById("registerForm");
register.addEventListener('submit', async function(e){
e.preventDefault();
functionSendForm();
})
function functionSendForm(){
let formData = new FormData();
formData.append('username', username.value);
formData.append('email', email.value);
fetch("../process/register.php",
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == true){
window.location.replace("sucess.php?userId=" + data.user);
return true;
} else {
document.getElementById("error").innerHTML = 'Sorry there was a problem. Please check the fields with red borders and correct these.';
return false;
}
});
}
if (callback) {
</C><br/>
to this:<br/>
<C>
if (typeof callback == 'function') {
`callback
</C>.<br/>
If it's not a function, the function checkUserName was called from the event listener, nothing has to be done.<br/>
If it's a function it was called directly on submit of the form like this:<br/>
<C>
checkUserName(checkAll);
` const register = document.getElementById("registerForm");
register.addEventListener('submit', async function(e){
e.preventDefault();
functionSendForm();
})
function checkAll() {
const form = document.querySelectorAll('form');
if (form.dataset.statusEmail == 'ok' && form.dataset.statusUsername == 'ok' && form.dataset.statusFirstname == 'ok'
&& form.dataset.statusLastname == 'ok'
) {
// All values are OK, submit form or transmit form data by ajax
//form.submit();
console.log('submitform');
} else {
console.log('errors')
}
}
let formData = new FormData();
formData.append('username', username.value);
formData.append('email', email.value);
formData.append('passwordconfirm', confirmPassword.value);
fetch("../process/register.php",
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == true){
window.location.replace("sucess.php?userId=" + data.user);
return true;
} else {
document.getElementById("error").innerHTML = 'Sorry there was a problem. Please check the fields with red borders and correct these.';
return false;
}
});
}
``<i>
</i> const
username = document.getElementById("username"),
email = document.getElementById("email"),
register = document.getElementById('registerForm');
username.addEventListener('focusout', checkUserName);
email.addEventListener('focusout', checkEmail);
register.addEventListener('submit', registerForm);
function registerForm(event) {
// Prevent default action (submitting the form) as we
// intend to send the data by ajax:
event.preventDefault();
// Call all checking functions. Every one will check
// if all values are OK and send the form if so:
checkEmail(checkAll);
checkUserName(checkAll);
}
function checkAll() {
if (register.dataset.statusUsername && register.dataset.statusUsername == 'ok' &&
register.dataset.statusEmail && register.dataset.statusEmail == 'ok') {
// All values are OK, submit form or transmit form data by ajax
sendForm();
console.log('submitform');
}
}
function checkEmail(callback) {
email.classList.remove('red')
email.classList.remove('green')
let formData = new FormData();
formData.append('email', email.value);
fetch("thread926-email.php?t=" + Date.now(),
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == 0) {
email.classList.add('green');
// callback handed over? This is the case
// if the form was submitted.
if (typeof callback == 'function') {
// note that email is OK:
register.dataset.statusEmail = 'ok';
// Now call callback in order to check
// if all values are OK and submit the form:
callback();
}
// return true;
} else {
email.classList.add('red')
// return false;
}
});
}
function checkUserName(callback) {
username.classList.remove('red')
username.classList.remove('green')
let formData = new FormData();
formData.append('username', username.value);
fetch("thread926-username.php?t=" + Date.now(),
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == 0) {
username.classList.add('green');
// callback handed over? This is the case
// if the form was submitted.
if (typeof callback == 'function') {
// note that email is OK:
register.dataset.statusUsername = 'ok';
// Now call callback in order to check
// if all values are OK and submit the form:
callback();
}
// return true;
} else {
username.classList.add('red')
// return false;
}
});
}
function sendForm() {
let formData = new FormData();
formData.append('username', username.value);
formData.append('email', email.value);
fetch("testpost.php",
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == true) {
window.location.replace("sucess.php?userId=" + data.user);
return true;
} else {
document.getElementById("error").innerHTML = 'Sorry there was a problem. Please check the fields with red borders and correct these.';
return false;
}
});
}<i>
</i>
``
async await
</C>. And it seems to me that this was true, no need for callbacks and storing results in data attributes:
<CODE>
`<i>
</i> const
username = document.getElementById("username"),
email = document.getElementById("email"),
register = document.getElementById('registerForm');
username.addEventListener('focusout', checkUserName);
email.addEventListener('focusout', checkEmail);
register.addEventListener('submit', registerForm);
async function checkAll() {
const
responseUsername = await checkUserName(),
responseEmail = await checkEmail(),
usernameOk = await responseUsername,
emailOk = await responseEmail;
if (usernameOk && emailOk) {
console.log('Values OK, send form');
sendForm();
}
}
function registerForm(event) {
// Prevent default action (submitting the form) as we
// intend to send the data by ajax:
event.preventDefault();
// Check all values, if all are OK the form will be submitted:
checkAll();
}
async function checkUserName() {
username.classList.remove('red')
username.classList.remove('green')
let formData = new FormData();
formData.append('username', username.value);
response = await fetch("thread926-username.php?t=" + Date.now(),
{
body: formData,
method: "post"
});
data = await response.json();
if (data.outcome == 0) {
username.classList.add('green');
return true;
} else {
username.classList.add('red')
return false;
}
}
async function checkEmail() {
email.classList.remove('red')
email.classList.remove('green')
let formData = new FormData();
formData.append('username', username.value);
const response = await fetch("thread926-email.php?t=" + Date.now(),
{
body: formData,
method: "post"
});
data = await response.json();
if (data.outcome == 0) {
email.classList.add('green');
return true;
} else {
email.classList.add('red')
return false;
}
}
function sendForm() {
let formData = new FormData();
formData.append('username', username.value);
formData.append('email', email.value);
fetch("testpost.php",
{
body: formData,
method: "post"
})
.then(response => response.json())
.then(data => {
if (data.outcome == true) {
window.location.replace("sucess.php?userId=" + data.user);
return true;
} else {
document.getElementById("error").innerHTML = 'Sorry there was a problem. Please check the fields with red borders and correct these.';
return false;
}
});
}<i>
</i>
````<i>
</i> responseUsername = await checkUserName(),
responseEmail = await checkEmail(),
usernameOk = await responseUsername,
emailOk = await responseEmail;<i>
</i>
`</CODE>
it's working synchronously: The response can be assigned to variables directly, no need for callbacks. However this code will only work inside an <C>
async
</C> function. When returning a value from that function it will be a promise and <C>
then
` has to be used in order to get the value.
0.1.9 — BETA 4.24