Currently, I am working on implementing AJAX for my contact form to send form data to the server. The objective is to have the server email me the user's information extracted from the input fields.
However, I'm encountering an issue where the formData appears to be functioning normally (seen in the browser network tab), but when I receive the email, the values are coming through as undefined.
const submit = document.querySelector('.contact-btn');
submit.addEventListener('click', send);
function send(event){
event.preventDefault();
const url = "https://us-central1-selexin-website.cloudfunctions.net/app/sendemail";
let form = document.querySelector('form');
let formData = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
console.log(formData)
// Display a green pop-up message below the textarea box notifying the user that the email was sent.
}
}
xhr.open('POST', url, true);
xhr.send(formData);
};
The following are the fields being emailed to me. As you can observe, I included "run test" within the email body as a string and it shows up perfectly in the email. Why then, is req.body returning undefined values?
const transport = nodemailer.createTransport(sendgridTransport({
auth: {
api_key: apiKey
},
}));
app.use(express.urlencoded({extended: false}));
app.use(cors({ origin: true }));
app.post('/sendemail', (req, res) => {
const {name, email, number, message} = req.body;
return transport.sendMail({
to: 'email receiving',
from: 'from this email',
subject: 'New Contact Request',
html: `
<p>You have a new Contact Request</p>
<h3>Contact Details</h3>
<ul>
<li>Name: 'Run test'</li>
<li>Email: ${email}</li>
<li>Number: ${number}</li>
<li>Message: ${message}</li>
</ul>
`
}).then(() => {
if(res.sendStatus(200)){
console.log('it logs');
};
})
});
exports.app=functions.https.onRequest(app);