I'm building a website for a friend. He has a basic "Contact Me" section. I'm wanting to use AJAX and PHP to submit the form.
Here is the form html.
div class="contactme" id="contactme">
<form class="form-horizontal" method="post" name="myemailform" id="myform" action="form-to-email.php">
<fieldset>
<h2>Let's Create Together</h2>
<hr class="small">
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">E-Mail</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="email" name="visitor_email" placeholder="E-Mail">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea class="form-control" rows="8" name="message"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="submit" name="submit" id="submitbutton" class="btn btn-primary mainButton">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
Here is jquery AJAX code snippet.
//AJAX FORM SUBMISSION
$(document).ready(function(){
$('#submitbutton').on('submit', function(){
//Stop the form from submitting itself to the server.
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
$.ajax({
type: "POST",
url: 'form-to-email.php',
data: {name: email},
success: function(){
alert(data);
}
});
});
});
And here is my PHP file that e-mails the responses from the user.
<?php
if (!isset ($_POST ['submit']))
{
//This page should not be accessed directly. Need to submist the form.
echo "error, you need to submit the form!";
}
$name = $_POST ['name'];
$visitor_email = $_POST ['visitor_email'];
$message = $_POST ['message'];
//Validation
if(empty ($name)||empty ($visitor_email))
{
echo "Name and email are mandatory!";
exit();
}
else {
echo "Submit Successful!";
header("Location: index.html");
exit();
}
$email_from = 'info@joshkelley.video'; //<== Put your email address here
$email_subject = "New Form Submission";
$email_body = "You have received a new message from the user $name.
".
"E-mail Address: $visitor_email
".
"Here is the message: $message
".
$to = "brandontetrick@gmail.com"; // <==Put your email address here
$headers = "From: $email_from
";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done
?>
Overall goal is for a basic submission of a "Contact Me" message, but the user doesn't leave the page. Every time I press the submit button, my validation fails and I get "Name and email are mandatory!" message.
The site is live if you want to take look. Still a work in progress. joshkelley.video