Question:
Where is the code off on this? I am trying to send a triggered email. Thank you!
Product:
WiX Studio and Code
What are you trying to achieve:
I am having issues with this code. Not sure where I am going wrong with it. thought is to create or update a contact and then send via a triggered email I created. But it is throwing coees
import { triggeredEmails } from 'wix-crm-frontend';
import { contacts } from 'wix-crm-frontend';
$w.onReady(function () {
// Assuming the dataset ID is "#dataset2"
$w("#dataset2").onAfterSave(() => {
// Get the values from the input fields
const preferredName = $w("#preferredName").value; // Get value from the "preferredName" input
const email = $w("#email").value; // Get value from the "email" input
// Prepare the dynamic values for the triggered email
const dynamicValues = {
"full name": preferredName, // Map the "preferredName" to "full name"
};
// Create or update the contact in Wix CRM before sending the email
createOrUpdateContact(email, preferredName, dynamicValues);
});
});
// Function to create or update a contact in Wix CRM
function createOrUpdateContact(email, preferredName, dynamicValues) {
contacts.queryContacts()
.eq("emails", email)
.find()
.then((results) => {
if (results.items.length > 0) {
// If contact exists, send the email
const contactId = results.items[0]._id;
sendEmailAfterSubmission(contactId, dynamicValues);
} else {
// If contact doesn't exist, create it
contacts.createContact({
emails: [email],
name: preferredName // Or other contact info
})
.then((newContact) => {
sendEmailAfterSubmission(newContact._id, dynamicValues);
});
}
})
.catch((error) => {
console.error("Error querying or creating contact:", error);
});
}
// Function to send the triggered email with dynamic content
function sendEmailAfterSubmission(contactId, dynamicValues) {
const emailId = "URqYHxi"; // Your unique triggered email ID
triggeredEmails.emailContact({
contactId: contactId, // Contact ID from Wix CRM
templateId: emailId, // Triggered email template ID
variables: dynamicValues // Send the dynamic values (like "full name") to the email template
})
.then(() => {
console.log("Triggered email sent successfully");
})
.catch((error) => {
console.error("Error sending triggered email:", error);
});
}