I have a form and a success/confirmation message that shows after a user submits the form.
When a user has completed the form before it gets their login information and logs them in, then populates the text elements within the success message using the database item they just created. (This all works fine)
If they haven’t filled out the form before (this means they are a new user) they are instead registered and then logged in.
The success message should then be populated with the database item they just created ( this isn’t working ).
After running it live with the dev console open, I can see that the function which registers and logs in the user (regiterUser) starts running… after which the populateRegConfirmation function starts running and completes… but the registerUser function is still running and doesn’t register/log the user in until after the populateRegConfirmation has completed.
I don’t know why this is happening… I’ve used await when calling the functions inside the form async function, so I would have thought this would make it run in order?
Here is the async function in which the two functions (registerUser & populateRegConfirmation) are called:
async function validateAndSubmitForm() {
// Hide the error state.
$w("#errorMessage").hide();
// List of fields in the booking form.
const formFields = ["firstNameInput", "lastNameInput", "phoneInput", "emailInput", "dobDatePicker", "genderDropdown", "addressInput", "cityInput", "postcodeInput", "ecNameInput", "ecRelationshipInput", "ecPhoneInput", "goalieRadioGroup", "skillRadioGroup", "waiverCheckbox", "emailsCheckbox", "termsCheckbox", "paymentDueInput" ];
let checked = [];
if ($w('#coedSpringCheckbox').checked)
checked.push(' Coed Spring 2021 ');
if ($w('#coedSummerCheckbox').checked)
checked.push(' Coed Summer 2021 ');
if ($w('#coedPackageCheckbox').checked)
checked.push(' Coed Spring & Summer 2021 ');
if ($w('#mensSpringCheckbox').checked)
checked.push(' Mens Spring 2021 ');
if ($w('#mensSummerCheckbox').checked)
checked.push(' Mens Summer 2021 ');
if ($w('#mensPackageCheckbox').checked)
checked.push(' Mens Spring & Summer 2021 ');
// If all the fields have valid values:
if (formFields.every(input => $w(`#${input}`).valid)) { // Create a new request item to be inserted in the pendingAppointments collection containing the form field
// values, and set its status to pending.
const newRequest = {
program: checked,
firstName: $w("#firstNameInput").value,
lastName: $w("#lastNameInput").value,
phone: $w("#phoneInput").value,
email: $w("#emailInput").value,
birthDate: $w("#dobDatePicker").value,
gender: $w("#genderDropdown").value,
address: $w("#addressInput").value,
city: $w("#cityInput").value,
postCode: $w("#postcodeInput").value,
emergencyContactName: $w("#ecNameInput").value,
emergencyContactRelationship: $w("#ecRelationshipInput").value,
emergencyContactPhone: $w("#ecPhoneInput").value,
goalkeeper: $w("#goalieRadioGroup").value,
skillLevel: $w("#skillRadioGroup").value,
paymentDue: $w("#paymentDueInput").value,
waiver: $w("#waiverCheckbox").value,
emailPermissions: $w("#emailsCheckbox").value,
termsPolicies: $w("#termsCheckbox").value
};
// Insert values into Soccer Members Database.
await wixData.insert("soccerMembersDatabase", newRequest);
// Refresh dataset.
await $w("#soccerMembersDataset").onAfterSave( () => {
console.log("After save")
});
$w("#soccerMembersDataset").refresh();
// Create new member using form values.
await registerUser();
// Insert reg confirmation details.
await populateRegConfirmation();
// Show the thank you state.
$w("#submitSuccessContainer").expand();
$w("#soccerRegistrationBox").collapse();
$w("#programSelectDropdown").hide();
$w("#submitSuccessAnchor").scrollTo();
$w("#registerButton").onClick((event) => {
$w("#submitSuccessContainer").collapse();
$w("#programSelectDropdown").show();
programSelectDropdown_change(event)
resetFormFields();
$w("#submitButton").enable();
});
}
// If some of the fields have invalid values:
else {
// Show the error state.
$w("#errorMessage").show();
$w("#submitButton").enable();
}
}
});
And here are the two functions themselves:
function registerUser() {
// Get user details for register or log in.
let phone = $w("#phoneInput").value;
let lastFourDigits = phone.substring(phone.length - 4, phone.length); //substring containing last 4 characters
console.log("Last 4 phone digits:",lastFourDigits);
let email = $w("#emailInput").value;
console.log("Registration email:", email);
let password = "GBSC" + lastFourDigits;
let firstName = $w("#firstNameInput").value;
let lastName = $w("#lastNameInput").value;
// Find if user has previously registered; if registered: log in, if not yet registered: register and then log in.
wixData.query('soccerMembersDatabase')
.eq('email', email)
.skip(1)
.find()
.then( (results) => {
console.log("SMDatabase query results:", results);
if(results.items.length > 0) {
wixUsers.login(email, password)
.then( () => {
console.log("Existing user is logged in");
} )
.catch( (err) => {
console.log("Existing user login error:", err);
} );
} else {
wixUsers.register(email, password, {
contactInfo: {
"firstName": firstName,
"lastName": lastName,
"phones": [phone]
}
} )
.then( (result) => {
let resultStatus = result.status;
console.log("Register new user result status:", resultStatus)
wixUsers.login(email, password)
.then( () => {
console.log("New user is logged in");
} )
.catch( (err) => {
console.log("New user login error:", err);
} );
} );
}
})
}
function populateRegConfirmation() {
if (($w("#programSelectDropdown").value==='Soccer')) {
let dobOptions = {day: "2-digit", month: "2-digit", year: "numeric"};
// Get current user.
let user = wixUsers.currentUser;
let userId = user.id;
user.getEmail()
.then((email) => {
let userEmail = email; // "user@something.com"
console.log("Current user email:", userEmail);
console.log(userId);
// Filter dataset to show items created by current user.
// get last item by current user.
wixData.query("soccerMembersDatabase")
.eq("email", userEmail)
.find()
.then( (results) => {
if(results.items.length > 0) {
let details = results.items[0];
$w("#name").text = details.firstName + " " + details.lastName;
$w("#phone").text = details.phone;
$w("#email").text = details.email;
$w("#address").text = details.address + ", " + details.city + ", " + details.postCode;
$w("#dob").text = details.birthDate.toLocaleDateString("en", dobOptions);
$w("#gender").text = details.gender;
$w("#ecName").text = details.emergencyContactName;
$w("#ecPhone").text = details.emergencyContactPhone;
$w("#ecRelationship").text = details.emergencyContactRelationship;
$w("#goalieStatus").text = details.goalkeeper;
$w("#skillLevel").text = details.skillLevel;
$w("#regRefNo").text = details._id;
$w("#program").text = details.program.toString();
$w("#totalDue").text = details.paymentDue;
console.log(details)
} else {
// handle case where no matching items found
}
} )
.catch( (err) => {
let errorMsg = err;
console.log(err);
} );
})
}
}
I have tried using callbacks and changing the order of other functions but nothing is working… Any help would be amazing!