I've set up a PHP script to collect "POST" data from a HTML form and send an email to a specific account with the data collected (a simple contact form).
I've created the PHP script which works correctly when the data is submitted using the submit button in the form, but want this takes me to a new page (the output of the PHP script).
I'd like to be able to keep this on one page, potentially displaying a message once the data has been sent correctly. I know I will need to use AJAX for this, so I've attempted to implement the jQuery AJAX method with little success.
When submitting the form, the page loads for a long time then quickly flashes an error message in the console before refreshing (I can't catch this error message to debug). Have I missed something in the JavaScript? Any assistance would be greatly appreciated.
My JS Code is as follows:
var submitBtn = $('#submit-form');
submitBtn.click(function(){
let email = $('#email'),
forename = $('#forename'),
surname = $('#surname'),
subject = $('#subject'),
message = $('#message');
// Send data to PHP script
$.ajax({
url: "submit_form.php",
method: 'POST',
data: {email: email, forename: forename, surname: surname, subject: subject, message: message}
});
});
My PHP Script:
$from_add = ; // Removed for security
$to_add = ; // Removed for security
$user_email = $_POST['email'];
$subject = $_POST['subject'];
$message = "You have received a message from {$_POST['forename']} {$_POST['surname']}:\n{$_POST['message']}";
$headers = "From: $from_add \r\n";
$headers .= "Reply-To: $user_email \r\n";
$headers .= "Return-Path: $from_add\r\n";
$headers .= "X-Mailer: PHP \r\n";
if(mail($to_add,$subject,$message,$headers))
{
echo "Email Sent";
}
else
{
echo "Error sending email!";
}
My HTML Form:
<form id="contact-form" class="contact-form">
<p class="field-label">First Name:</p>
<input class="input-field" type="text" id="forename" name="forename" placeholder="Please Enter Your First Name..." required>
<p class="field-label">Last Name:</p>
<input class="input-field" type="text" id="surname" name="surname" placeholder="Please Enter Your Last Name..." required>
<p class="field-label">Phone Number (Optional):</p>
<input class="input-field" type="text" id="phone" name="phone" placeholder="Please Enter Your Phone Number...">
<p class="field-label">Email Address:</p>
<input class="input-field" type="text" id="email" name="email" placeholder="Please Enter Your Email Address..." required>
<p class="field-label">Message Subject:</p>
<input class="input-field" type="text" id="subject" name="subject" placeholder="Message Subject" required>
<p class="field-label">Your Message:</p>
<textarea class="input-field" id="text-area" id="message" name="message" placeholder="Start typing your message here..." required></textarea>
<button id="submit-form" type="submit">Send Message</button>
</form>