Reputation: 69
I have written a method which sending an mail to my client in node.js like this :-
app.post('/sendemail',(req, res) => {
const output = `
<p>You have a new contact request</p>
<h3>Contact Details</h3>
<ul> ;
<li>Name: ${req.body.name}</li>
<li>Email: ${req.body.email}</li>
<li>Phone: ${req.body.phone}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({service: 'gmail ',
auth: {
user: '[email protected]',
pass: 'xxxxxxx'
},
tls:{
rejectUnauthorized:false
}
});
// setup email data with unicode symbols
let mailOptions = {
from: '"Enquiry from datadock" <[email protected]>', // sender address
to: '[email protected]', // list of receivers
subject: 'Datadock Enquiry ', // Subject line
text: 'Hello world?', // plain text body
html: output // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
res.send('error');
}
res.redirect('home.ejs',{message:"message sent"});
});
});
now i want to write an jquery function to read the response which i have sent from this method and show a modal , how can i write this code ? i have to use j query as using javascript is not possible due to many routes
Upvotes: 2
Views: 635
Reputation: 665
Because you are redirecting to a new router you will need to set the data you want to send to the frontend in a session. You can avoid this however by sending a response to the same router. To achieve this:
jQuery('button').on('click', function(event) {
event.preventDefault();
jQuery.ajax({
url: '/sendemail',
dataType: 'json',
success: function(data) {
alert(data.message);
jQuery('.yourModal').text(data.message).show();
/*setTimeout(function() {
//window.location.href = data.yourRedirectUrl;
}, 1000);*/
}
});
});
Then you'll need to replace the below:
res.redirect('home.ejs',{message:"message sent"})
With this:
res.end(JSON.stringify({message:"message sent", yourRedirectUrl: '/home'});
If you still need to redirect, you can uncomment the setTimeout
function I've added in the ajax script.
Edit: Alternatively you could just set your redirect to have a hash
res.redirect('home#mailsent',{message:"message sent"})
And put the following on home.ejs:
jQuery(document).on(‘load’, function(){
if(window.location.hash == ‘mailsent’) {
// Do stuff with your modal here
}
});
Upvotes: 1