I have created a contact form that sends a get request to a route I have hosted locally from a node(express) server. I send the get request when an element is clicked on the dom.
($(document).ready(function () {
$('#sendEmail').click((e) => {
e.preventDefault();
let name = $('#name').val();
let email = $('#email').val();
$.get("http://localhost:3000/send", {name: name, email: email})
.done(() => {
alert('success!');
})
.fail(() => {
alert('That did not work');
})
})($)
The node server generates an email based off of information that is gathered from the client. The good news is that the email that is generated works perfectly, and is emailed to my gmail account using nodemailer.
app.get('/send', (req, res) => {
const mailOptions = {
name: req.query.name,
email: req.query.email,
message: req.query.message,
to: "",
from: req.query.name,
text: ""
}
smtpTransport.sendMail(mailOptions, (error, response) => {
if (error) {
console.log(error);
response.end('error');
} else {
console.log('Email sent!');
response.end('sent')
}
})
})
Everything is successful server side but no client side code runs after that. Neither my $.done() function or my $.fail() function end up running. What do I need to do so that I can run client side code after the email sends (or doesn't send)?
Because you don't response the result to the client.
You need call 'res' instead of 'response' in the callback of 'sendMail':
app.get('/send', (req, res) => {
const mailOptions = {
name: req.query.name,
email: req.query.email,
message: req.query.message,
to: "",
from: req.query.name,
text: ""
}
smtpTransport.sendMail(mailOptions, (error, response) => {
if (error) {
console.log(error);
//response.end('error');
res.end('error'); // <=====================
} else {
console.log('Email sent!');
//response.end('sent')
res.end('Email sent!'); // <=====================
}
})
})