I created an email form on my website to collect emails using javascript and php. Initially, I attempted to prevent it from redirecting me to www.mywebsite.com/send_email.php by using fetch, but it still redirected me to another page that displayed the message ‘Message Sent! Thank you!’. Eventually, I managed to resolve the issue by embedding the script within the html file. However, I’m curious to know if there is a way to achieve the same outcome of loading on the same home page while keeping the javascript code in a separate js file linked to the html file.
const form = document.getElementById('myForm');
const messageDiv = document.getElementsByName('message');
const errorMessageDiv = document.getElementById('error-message');
form.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(form);
fetch('send_email.php', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error('Error sending email.');
}
})
.then(message => {
messageDiv.textContent = message;
messageDiv.style.display = 'block';
form.reset();
})
.catch(error => {
errorMessageDiv.textContent = 'Message Sent! Thank you!';
errorMessageDiv.style.display = 'block';
});
});
send_email.php
<?php
$to = '[email protected]';
$from = $_POST['email'];
$name = $_POST['username'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $from rn";
$headers .= "Reply-To: $from rn";
$body = "Name: $namen";
$body .= "Email: $fromn";
$body .= "Subjectt: $subjectn";
$body .= "Message:n$message";
if (mail($to, 'New Message from Your Website', $body, $headers)) {
echo "Message sent successfully!"; // Success message
} else {
echo "An error occurred while sending the email."; // Error message
}
echo json_encode($response);
?>
I tried to use fetch with the index.html but it still gives me the same result.
Express is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.