I'm setting up an extremely basic PHP/jQuery/Ajax contact form; and while it is working, the response is extremely slow (5+ seconds for the success message to show) and I'm wondering what I might be doing wrong.
Here is all the relevant code:
Markup:
<form id="contact-form" name="contact-form" action="php/form-process.php" method="post" role="form">
<input type="text" name="name" id="name" placeholder="Name" required>
<input type="email" name="email" id="email" placeholder="Email" required>
<textarea id="message" name="message" rows="5" placeholder="Your message" required></textarea>
<button type="submit" id="form-submit" class="contact-button">Submit</button>
<div id="msg-submit" class="hidden">Message sumbitted!</div>
</form>
PHP:
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "test@test.com";
$Subject = "New Contact Form Message";
// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success){
echo "success";
}else{
echo "invalid";
}
?>
jQuery:
$('#contact-form').submit(function(event){
event.preventDefault();
submitForm();
});
function submitForm(){
var $this = $('#contact-form');
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: $this.serialize(),
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$("#msg-submit").removeClass("hidden");
}
I'm leaving out all form validation functionality to stick to the absolute basics. I'm not sure if it's the server causing the slow response, but ideally, I'd like the success message to show as soon as the user clicks submit. Thanks for any assistance here.