i have a contact form and it sends just with php atm, i want to send it with ajax?
whats the easiest way?
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!$hasError) {
$emailTo = '123#gmail.com'; // Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
if(wp_mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
}else{
echo '<p class="alert-message error">Error sending mail.</p>';
}
}
}
?>
Please maybe give pointers on also improving the send function.
Any help really appreciated.
if you need to see the form let me know and i will edit and put it in
You can modify your code as follows.
Below is a stand-alone example (untested) of exactly what you requested.
Simply copy/paste the two code blocks into two files:
contacttest.php (or whatever you wish to call it)
yourphpprocessor.php (if change name, must also change it in AJAX code block)
Note that:
1. Each form element now has an ID attr
2. <form> functionality is no longer used at all, and is in fact prevented via e.preventDefault()
HTML: contacttest.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
$(document).ready(function() {
//If you want the output from php side in a lightbox...
$('#alertmsg').dialog({
autoOpen: false,
modal: true,
width: 400,
buttons: {
Thanks: function() {
$(this).dialog('close');
}
}
});
$('#contactform').submit(function(e) {
e.preventDefault();
var frm = $('#cname').val();
var eml = $('#cemail').val();
var sub = $('#subj').val();
var msg = $('#msg').val();
//validation goes here, for eg.
if (frm == '' || eml==''){
alert('All fields must be completed');
return false;
}
$.ajax({
type: "POST",
url: "yourphpprocessor.php",
data: 'f=' +frm+ '&e=' +eml+ '&s=' +sub+ '&m=' +msg,
success: function(recd) {
$('#alertmsg').html(recd);
$('#alertmsg').dialog('open'); //Uses lightbox to display message
}
});
}); //END AJAX
}); //END $(document).ready()
</script>
</head>
<body>
<form id="contactform" action="" method="POST">
From: <input type="text" name="contactname" id="cname"><br />
Email: <input type="text" name="email" id="cemail"><br />
Subject: <input type="text" name="subject" id="subj"><br />
Message: <textarea name="message" id="msg"></textarea><br /><br />
<input type="submit" id="mysubmit" value="Submit">
</form>
<div id="alertmsg"></div>
</body>
</html>
PHP Side: yourphpprocessor.php
<?php
$name = $_POST['f'];
$email = $_POST['e'];
$subject = $_POST['s'];
$comments = $_POST['m'];
$emailTo = '123#gmail.com'; // Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
if(wp_mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
}else{
echo '<p class="alert-message error">Error sending mail.</p>';
}
?>
You need to do this on the client side
Just use this plugin http://jquery.malsup.com/form/
Related
I am not well versed in this area and the other topics did not really help me. I tried using different portions to edit a PHP handler for a form and it did not work.
I get the email after the user clicks submit, however it is blank.
Also, this code i have has no validations for users trying to inject items.
Can someone help me add some validations and have the information appear in the email?
Any help is appreciated
EDIT NUMBER 2 SOLVED!:::::
Got the PHP and the JS talking nicely now. all is working. Had the wrong PHP file name in the JS code.
<?php
$errors = '';
$myemail = 'MYADDRESS';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact Form Submission: $name";
$email_body = "You have received a new submission from your website. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Phone: $phone \n Message: \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
// header('Location: index.html');
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Contact form handler</title>
</head>
<body>
<!-- This page is displayed only if there is some error -->
<?php
echo nl2br($errors);
?>
</body>
</html>
// JavaScript contact form Document
$(document).ready(function() {
$('form#contact-form').submit(function() {
$('form#contact-form .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if(jQuery.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'</span>');
$(this).addClass('inputError');
hasError = true;
} else if($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You entered an invalid '+labelText+'</span>');
$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {
$('form#contact-form input.submit').fadeOut('normal', function() {
$(this).parent().append('');
});
$("#loader").show();
$.ajax({
url: "contact-form-handler.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('form#contact-form').slideUp("fast", function() { $(this).before('<div class="col-lg-7 mx-auto success-box success"><img class="img-fluid" src="assets/img/support.png" alt=""><p>Thank you. Your Email was sent successfully. <br> <i class="icofont icofont-checked"></i></p> </div>');
$("#loader").hide();
})
}
});
return false;
}
});
});
I am having problem to see the problem with a pre-scripted template.
There are 3 files as follows,
/contact.php
/forms/contact.php
/js/forms.js
So when a visitor fills up the contact.php in root directory it redirects to /forms/contact.php and forms.js checks the form and if there is no problem sends an email.
Here is my /contact.php which includes the form,
<form id="contactform" method="post" action="forms/contact.php">
<div class="divide10"></div>
<input id="name" name="name" value="Your Name" type="text" class="prepared-input">
<div class="divide15"></div>
<input id="email" name="email" value="Your Email" type="text" class="prepared-input">
<div class="divide15"></div>
<textarea id="contactmessage" name="message" rows="3" class="prepared-input">Your Message</textarea>
<div class="divide15"></div>
<input type="submit" id="From_Comment_Go" value="Send Message " class="btn maincolor small">
<span class="errormessage hiddenatstart">Error! Please correct marked fields.</span>
<span class="successmessage hiddenatstart">Message send successfully!</span>
<span class="sendingmessage hiddenatstart">Sending...</span>
</form>
Here is my /forms/contact.php
<?php
$to = 'example#mail.com';
//Language Options
$contact_labelmailhead = 'Contact Form Email';
$contact_labelmailsubject = 'Contact Form Email from';
$contact_labelname = 'Name';
$contact_labelemail = 'Email';
$contact_labelmessage = 'Message';
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = str_replace(chr(10), "<br>", $_POST['message']);
$body = "<html><head><title>$contact_labelmailhead</title></head><body><br>";
$body .= "$contact_labelname: <b>" . $name . "</b><br>";
$body .= "$contact_labelemail <b>" . $email . "</b><br>";
$body .= "$contact_labelmessage:<br><hr><br><b>" . $message . "</b><br>";
$body .= "<br></body></html>";
$subject = $contact_labelmailsubject.' ' . $name;
$header = "From: $email\n" . "MIME-Version: 1.0\n" . "Content-type: text/html; charset=utf-8\n";
mail($to, $subject, $body, $header);
?>
and lastly forms.js is here,
jQuery(document).ready(function() {
/* Contact Form */
if(jQuery('#contactform').length != 0){
addForm('#contactform');
}
/* Quick Contact */
if(jQuery('#quickcontact').length != 0){
addForm('#quickcontact');
}
/* Blog Comments */
if(jQuery('#replyform').length != 0){
addForm('#replyform');
}
});
function addForm(formtype) {
var formid = jQuery(formtype);
var emailsend = false;
formid.find("input[type=submit]").click(sendemail);
function validator() {
var emailcheck = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var othercheck = /.{4}/;
var noerror = true;
formid.find(".requiredfield").each(function () {
var fieldname = jQuery(this).attr('name');
var value = jQuery(this).val();
if(value == "Name *" || value == "Email *" || value == "Message *"){
value = "";
}
if(fieldname == "email"){
if (!emailcheck.test(value)) {
jQuery(this).addClass("formerror");
noerror = false;
} else {
jQuery(this).removeClass("formerror");
}
}else{
if (!othercheck.test(value)) {
jQuery(this).addClass("formerror");
noerror = false;
} else {
jQuery(this).removeClass("formerror");
}
}
})
if(!noerror){
formid.find(".errormessage").fadeIn();
}
return noerror;
}
function resetform() {
formid.find("input").each(function () {
if(!jQuery(this).hasClass("button")) jQuery(this).val("");
})
formid.find("textarea").val("");
emailsend = false;
}
function sendemail() {
formid.find(".successmessage").hide();
var phpfile = "";
if(formtype=="#contactform"){
phpfile = "forms/contact.php";
}else if(formtype.lastIndexOf("c_")){
phpfile = "forms/quickcontact.php";
}else{
phpfile = "";
}
if (validator()) {
if(!emailsend){
emailsend = true;
formid.find(".errormessage").hide();
formid.find(".sendingmessage").show();
jQuery.post(phpfile, formid.serialize(), function() {
formid.find(".sendingmessage").hide();
formid.find(".successmessage").fadeIn();
if(!formtype.lastIndexOf("c_"))resetform();
});
}
}
return false
}
}
So, leaving the form sends Values :S and does not check anything. Shall I try to fix this or try to implement something else? I am not that into jQuery and cannot say if there is something wrong with validation script.
Some advice would be great!
Thank you!
There are errors on .js syntax, this could stop some js code from being called. First of all, fix these errors in js like this:
formid.find("input").each(function ()
{
if(!jQuery(this).hasClass("button")) jQuery(this).val("");
})//this is missing a ;
After that you can think properly on post method like Kevin Schmid said..
The validator function check each input with ".requiredfield" class.
Sample Code :
formid.find(".requiredfield").each(function () {
i am using correct code, still the ajax request is not sending the email content-- Can anyone have a look and suggest me what i can do better to get an email
Here is the form :
<form method="post" action="process.php">
<div class="element">
<label>Name</label>
<input type="text" name="name" class="text" />
</div>
<div class="element">
<label>Email</label>
<input type="text" name="email" class="text" />
</div>
<div class="element">
<label>Phone </label>
<input type="text" name="website" class="text" />
</div>
<div class="element">
<label>Comment</label>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
Here is the ajax request: --
<script type="text/javascript">
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website=' +
website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('enabled','false');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
</script>
and process.php as
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$website = ($_GET['website']) ?$_GET['website'] : $_POST['website'];
$comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Simple server side validation for POST data, of course, you should validate the email
if (!$name) $errors[count($errors)] = 'Please enter your name.';
if (!$email) $errors[count($errors)] = 'Please enter your email.';
if (!$comment) $errors[count($errors)] = 'Please enter your comment.';
//if the errors array is empty, send the mail / no errors found
if (!$errors) {
//recipient
$to = 'info#abc.com';
//sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Comment from ' . $name;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table>
<tr><td>Name</td><td>' . $name . '</td></tr>
<tr><td>Email</td><td>' . $email . '</td></tr>
<tr><td>Phone</td><td>' . $website . '</td></tr>
<tr><td>Comment</td><td>' . nl2br($comment) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
echo 'Thank you! We have received your message.';
//This one for ajax
//1 means success, 0 means failed
} else {
echo '1';
}
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
Any help in the end ? Thankyou
Please browse process.php?name=jone&email=john#example.com&website=www.blabla.com&comment=blablabla to know if the problem is in the server side script.
I have a contact form > www.bgv.co.za/testspace/contact_3.php
it uses jquery validate and PHP. I have some add/ remove class bits to hide or reveal a Thank you title and some php if isset to echo back the successful form submission inputs.
My problem is that on submission you see the thank you page but the div> sadhu is not showing the data that the user input... infact its not displaying as a div - please help
Here is my Jquery:
$(document).ready(function(){
$('#contactform').validate({
showErrors: function(errorMap, errorList) {
//restore the normal look
$('#contactform div.xrequired').removeClass('xrequired').addClass('_required');
//stop if everything is ok
if (errorList.length == 0) return;
//Iterate over the errors
for(var i = 0;i < errorList.length; i++)
$(errorList[i].element).parent().removeClass('_required').addClass('xrequired');
},
submitHandler: function(form) {
$('h1.success_').removeClass('success_').addClass('success_form');
$("#content").empty();
$("#content").append('#sadhu');
$('#contactform').hide();
var usr = document.getElementById('contactname').value;
var eml = document.getElementById('email').value;
var msg = document.getElementById('message').value;
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
form.submit();
}
});
});
Here is my PHP:
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
And here is my FORM:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform" >
<div class="_required"><p class="label_left">Name*</p><input type="text" size="50" name="contactname" id="contactname" value="" class="required" /></div><br/><br/>
<div class="_required"><p class="label_left">E-mail address*</p><input type="text" size="50" name="email" id="email" value="" class="required email" /></div><br/><br/>
<p class="label_left">Message</p><textarea rows="5" cols="50" name="message" id="message" class="required"></textarea><br/>
<input type="submit" value="submit" name="submit" id="submit" />
</form>
The <div id='sadhu'> is not defined anywhere. You're appending it to #content with Javascript code, but it doesn't exist.
$("#content").append('#sadhu');
You might want something like
$("#content").append("<div id='sadhu'>stuff in here...</div>");
You have placed the form entries into something with the id out. If that stuff should also be in <div id='sadhu'>, then you can just place the .html() of out into it:
document.getElementById('out').innerHTML = usr + " " + eml + msg;
document.getElementById('out').style.display = "block";
$("#content").append("<div id='sadhu'>" + $("#out").html() + "</div>");
I have a form which does everything right except send the input values to my email, what am I doing wrong? Ps: not using local server, so that's not it.
EDIT: I'm not getting any email whatsoever.
Tried changing the if(isset($_POST['enviar'])) { part but still not working.
Tried the chatty echos. the only if statement that isn't behaving properly is stripslashes. It stops at the else statement.
The form snippet:
<div id="contact-wrapper">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you entered valid information.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Email sent with success!</strong></p>
<p>Thank you for using our contact form <strong><?php echo $name;?></strong>, we will contact you soon.</p>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<div>
<label for="name"><strong>Name:</strong></label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
</div>
<div>
<label for="email"><strong>E-mail:</strong></label>
<input type="text" size="50" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject"><strong>Subject:</strong></label>
<input type="text" size="50" name="subject" id="subject" value="" class="required" />
</div>
<div>
<label for="message"><strong>Message:</strong></label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
</div>
<input type="submit" value="enviar" name="submit" id="submit" />
</form>
</div>
and the PHP:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure that the subject field is not empty
if(trim($_POST['subject']) == '') {
$hasError = true;
} else {
$subject = trim($_POST['subject']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
The ereg() family of functions are deprecated. use the preg_...() equivalents instead. They work almost exactly the same, except requiring delimiters around the match patterns.
As well, don't use PHP_SELF in your form. That value is raw user-supplied data and can be trivially subverted for an XSS attack.
Checking for a particular form field to see if a POST occured is somewhat unreliable - you might change the field's name later on and your check will fail. However, this
if ($_SERVER['REQUEST_METHOD'] == 'POST) { ... }
will always work, no matter how many or few fields are in the form, as long as the form was actually POSTed.
As for the actual problem, I'm assuming the mail is getting sent out, or you'd have complained about that. That means your variables aren't being populated properly. Instead of just sending the mail, echo out the various variables as they're built, something like:
echo 'Checking name';
if ($_POST['name'] .....) {
echo 'name is blank';
} else {
$name = ...;
echo "Found name=$name";
}
Basically have your code become extremely "chatty" and tell you what it's doing at each stage.
#dafz: Change
if(isset($_POST['submit'])) {
to
if(isset($_POST['enviar'])) {
#Marc B deserves another up-vote for his answer as well.
Edit
You can try the following update.
if(!isset($hasError)) {
$siteAddress = 'validaddress#yourdomain.com'; //Put admin# or info# your domain here
$emailTo = 'myemail#email.com'; //Put your own email address here
$body = "Name: $name \r\nEmail: $email \r\nSubject: $subject \r\nComments: $comments \r\n";
$headers = 'To: ' . $name . ' <' . $emailTo . '>' . "\r\n";
$headers .= 'From: My Site <' . $siteAddress . '>' . "\r\n";
$headers .= 'Reply-To: ' . $email . "\r\n";
if (mail($emailTo, $subject, $body, $headers)) {
$emailSent = true;
} else {
$emailSent = false;
}
}