"Failed to fetch" when sending triggered email

I’ve a problem at sending triggered e-mails to contacts. I’ve searched for hours and hours couldn’t find anything I’ve done everything same as the docs and some tutorials but error still occurs.

Here’s my code;

wixCRM.createContact({
 "firstName": $w('#nameInput').value,
 "emails": [$w("#mailInput").value]
    }).then((contactId) => {
        console.log(contactId);
        wixCRM.emailContact("booked_mail", contactId, {
 "variables": {
 "name": $w('#nameInput').value,
 "phone": $w('#numberInput').value,
 "email": $w('#mailInput'),
 "from": From,
 "to": to,
 "vehicle": vehicle,
 "pax": passengers,
 "date": $w('#arrivalDate'),
 "time": $w('#arrivalTime'),
 "price": price
            }
        }).then(() =>{
 //success.
        console.log("mail has been send");
    })
    .catch((error) => {
        console.log("error: " + error.message);             
        })
    });

You need to add an onAfterSave event handler function to that code so that it all runs after the form has been submitted and saved into your dataset.
https://www.wix.com/corvid/reference/wix-dataset.Dataset.html#onAfterSave

onAfterSave( )
Adds an event handler that runs just after a save.
Description
The onAfterSave() function allows you to optionally perform actions right after a save() operation. When you call save(), the callback is run after the save has successfully completed.
Calling onAfterSave() on a read-only dataset causes an error.

Examples

Register a callback to run after a save

$w("#myDataset").onAfterSave( () => {
  console.log("After save");
} );

I have done similar for a Choir website, have a look at code here.

import wixCRM from 'wix-crm';

$w.onReady(function () {
$w("#JoinUsForm").onAfterSave(() => {
let startDate = $w("#startDate").value;
let firstName = $w('#firstName').value;
let lastName = $w('#lastName').value;
let email = $w("#email").value;
let choirRole = $w("#choirRole").value;
let readMusic = $w("#readMusic").value;
let choirBefore = $w("#choirBefore").value;
let startNow = $w("#startNow").value;

wixCRM.createContact({ 
"firstName": firstName,
"lastName": lastName,
"emails": [email],
"Choir Role": choirRole,
"Read Music": readMusic,
"Choir Before": choirBefore,
"Start Now": startNow,
"Start Date": startDate
}) 
.then((contactId) => { 
// Need to use the triggered email name
return wixCRM.emailContact('joiningusform', contactId, { 
"variables": { 
// Need to use the triggered email variable names
"firstName": firstName,
//"lastName": $w('#lastName').value, << - not defined in the triggered email
//"emails": [$w("#email").value], << - cannot have array here
"email": email, // << - correct variable is email not emails
"choirRole": choirRole,
"readMusic": readMusic,
"choirBefore": choirBefore,
"startNow": startNow,
"startDate": startDate.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric'})
} 
}); 
}) 
.catch((err) => { 
// handle the error if the email wasn't sent
console.log(`Error: ${err}`);
}); 
}); 
}); 

@givemeawhisky
Thank you for your answer!

Actually I am not getting any data from database to e-mail so I didn’t understand why I need wait for it. Also I can send e-mail without saving any data. Can you be more specific.

@givemeawhisky Also we have same syntax to sending e-mail and many other devs on youtube, forum etc. I still don’t get it why it isn’t working.

@givemeawhisky I am not saving my data with dataset. I am using query wix-data so I dont need to save any dataset. So I think onAfterSave is not necessary.

So if I get this right, you are having a user submit a form, yet you are not saving it to a dataset and yet you are using Wix Data and it’s query function to run a query on a dataset.

If you are not using user inputs to submit a form, then you shouldn’t be using the exact code as shown from the tutorial.
https://support.wix.com/en/article/corvid-tutorial-sending-a-triggered-email-to-contacts

That triggered email to contacts tutorial clearly states…

Triggered Emails allow you to create a template for emails that you can send to a newly created contact, using code. Before sending the email, your code can inject information into the template to personalize it with any data that is available in your page code. In this article, we demonstrate how to use the code snippet generated by Triggered Emails to send an email to the newly created contact on the submission of a form.

Although this article uses a form submission for demonstration purposes, you can send an email from anywhere in your code. The general idea is to paste the generated snippet into your code where you want the email to be sent. Then edit the snippet so that it uses the ID of the newly created contact and the values you want to insert for the variable placeholders.

In this article, we demonstrate how to use the code snippet generated by Triggered Emails to send an email to the newly created contact on the submission of a form.
Hence why you need the onAfterSave event handler function to run the code after the user inputs have been submitted to your dataset.

Plus, as you say that you run a Wix Data query, where is that shown in your code as there is only the code snippets from the tutorial. To see why your code is not working for you, we need to see all the code that you have used and not just part of it.

If you are still struggling and want an easy route then just use Wix Automations for a reply back to them.
https://support.wix.com/en/article/about-wix-automations

This is from the same site as the code sample from above and you can see it is still done after a onAfterSave which runs after the user inputs are saved into the dataset.

import wixCRM from 'wix-crm';

$w.onReady(function () {
$w("#PublicContactUs").onAfterSave(() => {
let name = $w('#publiccontactName').value;
let email = $w("#publiccontactEmail").value;
let subject = $w("#publiccontactSubject").value;
let message = $w("#publiccontactMessage").value;
let label = ["Contacted Us"];

wixCRM.createContact({ 
"name": name,
"emails": [email]

}) 
.then((contactId) => { 
// Need to use the triggered email name
return wixCRM.emailContact('publiccontactus', contactId, { 
"variables": { 
// Need to use the triggered email variable names
"name": name,
"email": email, // << - correct variable is email not emails
"subject": subject,
"message": message
} 
}); 
}) 
.catch((err) => { 
// handle the error if the email wasn't sent
console.log(`Error: ${err}`);
}); 
}); 
}); 

$w("#NewSubscriber").onAfterSave(() => {
let name = $w("#newsubscriberName").value;
let email = $w("#newsubscriberEmail").value;
let privacyPolicy = $w("#newsubscriberPrivacy").value;
let label = ["Subscribed"];

wixCRM.createContact({ 
"name": name,
"emails": [email]

}) 
.then((contactId) => { 
// Need to use the triggered email name
return wixCRM.emailContact('newsubscriber', contactId, { 
"variables": { 
// Need to use the triggered email variable names
"name": name,
"email": email, // << - correct variable is email not emails
//"privacyPolicy": privacyPolicy << - not defined in the triggered email
} 
}); 
}) 
.catch((err) => { 
// handle the error if the email wasn't sent
console.log(`Error: ${err}`);
}); 
}); 

You can also just look at the Wix CRM API Reference and you would have found a suitable example for yourself there, which uses a onClick event handler function instead of the onAfterSave.
https://www.wix.com/corvid/reference/wix-crm.html#createContact

Create a contact and then send a Triggered Email to the new contact

import wixCRM from 'wix-crm';

$w.onReady(function () {
  $w("#myButton").onClick( () => {
    wixCRM.createContact( {
      "firstName": $w("#firstName").value,
      "lastName": $w("#lastName").value,
      "emails": [$w("#email").value],
      "phones": [$w("#phone").value]
    } )
    .then( (contactId) => {
      wixCRM.emailContact("thankyou", contactId, {
        "variables": {
          "firstName": $w("#firstName").value,
          "lastName": $w("#lastName").value
        }
      } );
    } );
  } );
} );
1 Like

@givemeawhisky User books service from my site so I have user input. I juwt want to send mail like a bill. User fill the form name, mail, date etc. and I am sending the information which user fill + price of service. And again you copy pasted same syntax to me. I am using exact same code on buttonClick and still getting the error. Forget the database I have no buisness with database. I just want to send the information which user fill on the form to send back to him like a bill.

Here is my “buttonClick” code “again” which is the “same” code you write and “still” getting the error. Pls look at it I may miss something so you can correct me if I am.

export function bookBtn_click(event) {
 //Creating contact to send e-mail.
    wixCRM.createContact({
 "firstName": $w('#nameInput').value,
 "emails": [$w("#mailInput").value]
    })
    .then((contactId) => {
        console.log("Sending mail to: "+ contactId);
        wixCRM.emailContact("booked_mail", contactId, {
 "variables": {
 "name": $w('#nameInput').value,
 "phone": $w('#numberInput').value,
 "email": $w('#mailInput'),
 "from": From,
 "to": to,
 "vehicle": vehicle,
 "pax": passengers,
 "date": $w('#arrivalDate'),
 "time": $w('#arrivalTime'),
 "price": price
            }
        })
        .then(() =>{
 //success.
        console.log("Mail has been send.");
    })
    .catch((error) => {
        console.log("There was an error while sending mail to : " +contactId + ". Error: " + error.message);                
        });
    }); 
}

@givemeawhisky Also I saw all the documents about creating contact and sending mail to contact which wix shared.

Still have the issue any help?

Any help? I think this is a real bug and wix supporters won’t help me. This is a serious problem for my company and I need to solve it.

It is not a bug, you simply need to use a dataset on your page to save your user inputs from your form. Without a dataset, you are not going to get any values sent in your triggered email.

See here about creating a user input form.
https://support.wix.com/en/article/creating-a-form-with-user-input-elements

Hence why I said in previous posts that you need to use onAfterSave.

I’m having the same problem. I tried using “onAfterSave” and it did not help. I am receiving an “TypeError: failed to fetch” after running the following code:

let firstName = $w('#firstName').value;
let email = $w("#email").value;
wixCRM.createContact({
  "firstName": firstName,
  "emails": [email]
})
.then((contactId) => {
  wixCRM.emailContact(triggerEmailID, contactId, {
    "variables": {
      "firstName": "eric"
    }
  })
  .then( () => {
    console.log("success");
    wixLocation.to(linkPage);
  })
  .catch((err) => {
    console.log("reached3");
    console.log(email);
    console.log(triggerEmailID);
    console.log(contactId);
    console.log(err);
  });
});

Is this line correct?

wixCRM.emailContact(triggerEmailID, contactId, {

Is ‘triggerEmailID’ the name of your triggered email that you have used?

Suggest you go back and read the tutorial again.

I’m using this code but still no luck

export function sendEmail_click(event) {
$w("#dataset1").onAfterSave(() => {
let contactInfo = {
"emails": [$w('#inputEmail').value]
};
console.log(contactInfo);
wixCrm.createContact(contactInfo)
.then((contactId) => {
console.log(contactId);
return wixCrm.emailContact('Ru2ePvr', contactId)
.then(() => {
console.log('Triggered email sent')
$w('#inputEmail').value = '';
})
.catch((error) => {
console.log(`Error: ${error}`)
$w('#inputEmail').value = '';
})
})
})
}

This is an old thread and is being closed.

Please repost your question with more details: what are you trying to do, what works, what doesn’t.