/    Sign up×
Community /Pin to ProfileBookmark

Multiple functions have conditions met

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!’)
}
“`

to post a comment
JavaScript

22 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMay 08.2022 — >it's because my code isn't waiting for my fetch to return

I suspect the same. Generally you have to perform all actions that need the server's response in the `then` callback.

Is the form submitted directly or is the data sent to the server by use of Ajax?
Copy linkTweet thisAlerts:
@SempervivumMay 08.2022 — One option to do this (not tested):
``<i>
</i> function checkAll() {
const form = document.querySelectorAll('form');
if (form.dataset.statusEmail == 'ok'
&amp;&amp; form.dataset.statusLastName == 'ok'
&amp;&amp; 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 =&gt; response.json())
.then(data =&gt; {
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.
Copy linkTweet thisAlerts:
@kiwisauthorMay 09.2022 — @Sempervivum#1643886

For this to happen, do I need to add a dataset element for each field into the form tag or input tag?

I'm getting this error when using this function on focusout

index.php:277 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'statusUsername')

at index.php:277:86
Copy linkTweet thisAlerts:
@SempervivumMay 09.2022 — My bad, querySelectorAll is wrong in this context, has to read:

`document.querySelector('form').dataset.statusEmail = 'ok';`

This line adds a dataset element, you need not do this manually.
Copy linkTweet thisAlerts:
@kiwisauthorMay 09.2022 — Right then callback?

index.php:281 Uncaught (in promise) TypeError: callback is not a function

at index.php:281:29
Copy linkTweet thisAlerts:
@SempervivumMay 09.2022 — Did you define the function checkAll()? (First block of code)
Copy linkTweet thisAlerts:
@kiwisauthorMay 10.2022 — Yes, this is what I have.

Still saying "Uncaught (in promise) TypeError: callback is not a function"

What is callback? seems like a function which I've not declared

``<i>
</i>function checkAll() {
const form = document.querySelectorAll('form');
if (form.dataset.statusEmail == 'ok' &amp;&amp; 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 =&gt; response.json())
.then(data =&gt; {
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 =&gt; response.json())
.then(data =&gt; {
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>
``
Copy linkTweet thisAlerts:
@SempervivumMay 10.2022 — OK, the function checkAll is defined. How do you call checkUserName?
Copy linkTweet thisAlerts:
@kiwisauthorMay 10.2022 — @Sempervivum#1643912

const username = document.getElementById("username");
username.addEventListener('focusout', checkUserName);
Copy linkTweet thisAlerts:
@SempervivumMay 10.2022 — That's OK, do you call the function a second time when the submit button is pressed?
Copy linkTweet thisAlerts:
@kiwisauthorMay 10.2022 — No, I don't believe I am now I look closer...

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

}
Copy linkTweet thisAlerts:
@SempervivumMay 10.2022 — I'm gonna have to create some test setup. Will take some time ...
Copy linkTweet thisAlerts:
@SempervivumMay 10.2022 — ... done. My bad again: When using checkUserName as a callback function for an event listener, the first parameter is not undefined but it's the event instead. Change this line:

` if (callback) {</C><br/>
to this:<br/>
<C>
if (typeof callback == 'function') {`
Copy linkTweet thisAlerts:
@kiwisauthorMay 10.2022 — Seems to work, what exactly is it doing?
Copy linkTweet thisAlerts:
@SempervivumMay 10.2022 — It checks the type of the first parameter `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);`
Copy linkTweet thisAlerts:
@kiwisauthorMay 10.2022 — So it works well. But if I submit the for, I go direct into the functionSendForm function,

I think i need the if (typeof callback == 'function') { in here as well?

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')
}
}


function functionSendForm(){

console.log('trying to send');

const dob = document.getElementById("dob");

const gender = document.getElementsByName("gender");

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

}
Copy linkTweet thisAlerts:
@SempervivumMay 10.2022 — I got it working, read my remarks in the code in order to understand:
``<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 &amp;&amp; register.dataset.statusUsername == 'ok' &amp;&amp;
register.dataset.statusEmail &amp;&amp; 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 =&gt; response.json())
.then(data =&gt; {
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 =&gt; response.json())
.then(data =&gt; {
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 =&gt; response.json())
.then(data =&gt; {
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>
``

Note that I used some test scripts, you have to change back the URLs.
Copy linkTweet thisAlerts:
@SempervivumMay 10.2022 — When writing the previous code I suspected that it might be easier by use of `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 &amp;&amp; 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 =&gt; response.json())
.then(data =&gt; {
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>
``
Copy linkTweet thisAlerts:
@kiwisauthorMay 11.2022 — @Sempervivum#1643934

Thanks for this, I'll take a look tomorrow.

So essentially you're making the JS wait for a response? then doing a basic check to see it each one is true once you have each response?
Copy linkTweet thisAlerts:
@SempervivumMay 12.2022 — Yes. When using this code:
``<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.
Copy linkTweet thisAlerts:
@kiwisauthorMay 14.2022 — I've got this working with a few extra fields as well, simply amazing!!
Copy linkTweet thisAlerts:
@StevenMBrunMay 19.2022 — Thank you for interesting article
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...