this form is sending data to database but i need the query should also go to the two other ids someone said use smtp but i don't know how and where to add smtp in this form. please help thanks in advance
<?php
// Attention! Please read the following.
// It is important you do not edit pieces of code that aren't tagged as a configurable options identified by the following:
// Configuration option.
// Each option that is easily editable has a modified example given.
$error = '';
$name = '';
$email = '';
$organisation = '';
$phone = '';
$subject = '';
$comments = '';
//$verify = '';
if(isset($_POST['contactus'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$organisation = $_POST['name'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
//$verify = $_POST['verify'];
$servername = "localhost";
$username = "auweb";
$password = "auw3b";
$dbname = "auweb";
$useragent=$_SERVER['HTTP_USER_AGENT'];
$ip=$_SERVER['REMOTE_ADDR'];
//echo $msg;
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
}
$sql="";
if(empty($name)||empty($phone)||empty($email)||empty($subject)||empty($comments)){
$sql = "INSERT INTO `aki_logs` (`ts`, `name`, `email`, `phone`, `state`, `course`, `useragent`, `ip`, `status`)VALUES (now(), '$name', '$email', '$phone', '$comments', '$subject', '$useragent', '$ip', 'Error');";
//echo 'Please enter all the data';
header('location:index.php');
}
else{
$sql = "INSERT INTO `aki_logs` (`ts`, `name`, `email`, `phone`, `state`, `course`, `useragent`, `ip`, `status`)VALUES (now(), '$name', '$email', '$phone', '$comments', '$subject', '$useragent', '$ip', 'Success');";
}
$conn->query($sql);
$conn->close();
//$to="admissions2#ansaluniversity.edu.in,siddhartha#digidarts.com";
//$to='admissions2#ansaluniversity.edu.in';
#date_default_timezone_set('Asia/Kolkata');
#session_start();
unset($_POST['formname']); unset($_POST['submit']);
$csv = implode('","', $_POST);
$csv = '"'.date("d-m-Y").'","'. date("H:i:s") .'","' . $csv . '"' . "\r\n";
$file = '../../data/'. basename( __DIR__ ) .'.csv';
#file_put_contents($file, $csv, FILE_APPEND);
// Configuration option.
// You may change the error messages below.
// e.g. $error = 'Attention! This is a customised error message!';
if(trim($name) == '') {
$error = '<div class="error_message">Attention! You must enter your name.</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Attention! Please enter a valid email address.</div>';
// Configuration option.
// Remove the // tags below to active phone number.
} else if(!is_numeric($phone)) {
// $error = '<div class="error_message">Attention! Phone number can only contain digits.</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>';
}
if(trim($organisation) == '') {
$error = '<div class="error_message">Attention! Please enter a subject.</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">Attention! Please enter your message.</div>';
}// else if(trim($verify) == '') {
// $error = '<div class="error_message">Attention! Please enter the verification number.</div>';
//} else if(trim($verify) != '4') {
// $error = '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
//}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "";
$address = "mk#gmail.com, mk2#gmail.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_organisation = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name with regards to $organisation, their additional message is as follows.\r\n\n";
$e_content = "\"$comments\"\r\n\n";
// Configuration option.
// RIf you active phone number, swap the tags of $e-reply below to include phone number.
$e_reply = "You can contact $name via email, $email or via phone $phone";
//$e_reply = "You can contact $name via email, $email";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_organisation, $msg, "From: 'enquiry#gmail.com'\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
// Email has sent successfully, echo a success page.
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php echo $error; ?>
<fieldset>
<legend>Please fill in the following form to contact us</legend>
<form method="post" action="#succsess_page">
<div class="row">
<div class="col-md-6">
<label for=name accesskey=U><span class="required">*</span> Your Name</label>
<input name="name" type="text" id="name" size="30" value="<?php echo $name; ?>" />
<br />
<label for=email accesskey=E><span class="required">*</span> Email</label>
<input name="email" type="text" id="email" size="30" value="<?php echo $email; ?>" />
<br />
<label for=phone accesskey=P><span class="required">*</span> Phone</label>
<input name="phone" type="text" id="phone" size="30" value="<?php echo $phone; ?>" />
</div><!--COL-FORM HALF-->
<div class="col-md-6">
<label for=subject accesskey=S><span class="required">*</span> Subject</label>
<select name="subject" id="subject">
<option value="B. A. (Hons) - Liberal Arts">B. A. (Hons) - Liberal Arts</option>
</select>
<br />
<label for=comments accesskey=C><span class="required">*</span> Query</label>
<textarea name="comments" cols="30" rows="3" id="comments"><?php echo $comments; ?></textarea>
<hr />
<!--<p><span class="required">*</span> Are you human?</p>
<label for=verify accesskey=V> 3 + 1 =</label>
<input name="verify" type="text" id="verify" size="4" value="<?php echo $verify; ?>" /><br /><br />-->
<input name="contactus" type="submit" class="submit" id="contactus" value="Submit" />
</div>
</div>
</form>
</fieldset>
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
?>
If you should send an email after form submitting, you can use the php "mail()" function (http://php.net/manual/en/function.mail.php).
Or, if you wanna use SMTP protocol you should integrate in your project a plugins like PHPMailer. See ya!
Related
I am new to PHP and jQuery. I wanted to test the functionality for the email contact form in PHP that I call from my jQuery file. I have been filling in the details on the form correctly, however, whenever I press the "Submit" button, I get 405 error.
To be more precise, I get "POST http://192.168.87.1:8080/js/inc/contactformhandler.php 405 (Method Not Allowed)" from jquery-3.4.1.min.js:2. I am running my website on http-server !.
My HTML form:
<div class="row contact-form">
<div class="col-twelve">
<!-- form -->
<form name="contactForm" id="contactForm" method="POST">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required="">
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required="">
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="message" rows="10" cols="50" required=""></textarea>
</div>
<div class="form-field">
<button class="submitform">Submit</button>
<div id="submit-loader">
<div class="text-loader">Sending...</div>
<div class="s-loader">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
</fieldset>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning">
</div>
<!-- contact-success -->
<div id="message-success">
<i class="fa fa-check"></i>Your message was sent, thank you!<br>
</div>
</div> <!-- /col-twelve -->
</div> <!-- /contact-form -->
JS code where I try to load the contactformhandler.php:
/* local validation */
$('#contactForm').validate({
/* submit via ajax */
submitHandler: function(form) {
var sLoader = $('#submit-loader');
$.ajax({
type: "POST",
url: "js/inc/contactformhandler.php",
data: $(form).serialize(),
beforeSend: function() {
sLoader.fadeIn();
},
success: function(msg) {
// Message was sent
if (msg == 'OK') {
sLoader.fadeOut();
$('#message-warning').hide();
$('#contactForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
sLoader.fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}
},
error: function() {
sLoader.fadeOut();
$('#message-warning').html("Something went wrong with loader. Please try again.");
$('#message-warning').fadeIn();
}
});
}
});
contactformhandler.php:
<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
// Replace this with your own email address
$siteOwnersEmail = 'krysbaran#gmail.com';
if(isset($_POST["submit"])) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (!$error) {
mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'MyWebsiteEmail';
$mail->Password = 'MyPassword';
$mail->SMTPSecure = 'ssl'; //<---- THIS is the problem
$mail->Port = 465;
$mail->setFrom('MyWebsiteEmail', 'My Website');
$mail->addAddress($siteOwnersEmail, 'Krzysztof Baran');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'test text';
try {
$mail->send();
echo 'OK';
}
catch (phpmailerException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
$e->getMessage();
}
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
I expect the website to display box saying Your message was sent, thank you! but I am getting Something went wrong with loader. Please try again.
You should use form in .php file not in .html file
The following form works as intended, including the honeypot, but if someone clicks on Refresh in the browser prior to finishing the form, it tries to resubmit. I have tried sessions but it is not working. Does anyone know how I can make the page redirect back to contact.php or end the session so it does not resubmit on refresh in the browser? ( I have spent 2 days searching for answers ). Thanks
Code:
<!--form-->
<?php
//fields
$link_address = 'contact.php'; // page to redirect to home page
$honeypot = '';
$error = '';
$name = 'Name (required)';
$email = 'Email (required)';
$comments = 'Message (required)';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['honeypot'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
//error messages
if(trim($name) == 'Name (required)') {
$error = '<div class="error_message">Please enter your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Please enter your Name</div>';
} else if(trim($email) == 'Email (required)') {
$error = '<div class="error_message">Please enter an email address</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Please enter an email address</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Please enter a valid email address</div>';
} else if(trim($comments) == 'Message (required)') {
$error = '<div class="error_message">Please enter a Message</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">Please enter a Message</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "email#youremail.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='success_page'>";
echo "<div id='thanks'>";
echo "<h1>Message Sent Successfully.</h1>";
echo "<p id='cprint1'>Thank you. Your message was sent to us. </br>We will be in touch shortly.</p>";
echo "<p id='print'><a href='javascript:window.print()'>Print your Message</a></p>";
echo "<p id='cclose'><a href='$link_address'>Close this Message</a></p>";
echo "</div>";
echo "<div id='thanks2'>";
echo "<div id='titlemsg'>Below is your message</div>";
echo "<p><span>Name:</span> $name</p>";
echo "<p><span>Email:</span> $email</p>";
echo "<p><span>Message:</span>$comments</p>";
echo "</div>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<!--form-->
<form method="post" action="" id="myform" autocomplete="off">
<div id="error"><?php echo $error; ?></div>
<input name="name" type="text" id="name" class="form1"
value="<?php echo $name; ?>" onfocus="if(this.value == 'Name (required)') {this.value = ''; }" onblur="if(this.value == '') { this.value = 'Name (required)'; }" value="Name (required)" />
<input name="email" type="text" id="email" class="form1"
value="<?php echo $email; ?>" onfocus="if(this.value == 'Email (required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Email (required)'; }" value="Email (required)" />
<input name="honeypot" type="text" id="honeypot" class="form2" value="<?php echo $honeypot; ?>" />
<textarea name="comments" cols="40" rows="3" id="comments"
value="<?php echo $comments; ?>" onfocus="if(this.value == 'Message (required)') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Message (required)'; }" value="Message (required)"><?php echo $comments; ?></textarea>
<input name="contactus" type="submit" class="submit" id="contactus" value="Contact us" />
</form>
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>
You can save your message in session on successfull mail sent. and then refresh your page and check if session exist then show message and reset session.
Just redirect it to the same page after making the use of form data.
Example-
header('location:yourpage.php');
and you can also unset $_POST after inserting it to Database.
unset($_POST);
You can use the javascript redirect:
<script>
window.location.href = 'test.php';
</script>
I've a website since 2013. I've signed up quite 12k users. From 5 months I have noticed some blank users. They receive a user-code but "name" "surname" and "email" fields are blanks.
This event happen every 50/100 users registrations. Why? I have tried everything, but in all test I can't sign up without data. Also other people that have made tests can't sign up without insert data.
This is the form:
<form action="script/****.php" method="post" onsubmit="return validate()">
<label for="name">Name</label>
<input type="text" id="name" name="name" <?php if($_REQUEST['name'] != "") echo "value='".$_REQUEST['name']."'"; ?> />
<label for="surname">Surname</label>
<input type="text" id="surname" name="surname" <?php if($_REQUEST['surname'] != "") echo "value='".$_REQUEST['surname']."'"; ?> />
<label for="email">Email</label>
<input type="email" id="email" name="email" <?php if($_REQUEST['email'] != "") echo "value='".$_REQUEST['email']."'"; ?> />
<label for="c_email">Retype Email</label>
<input type="email" id="c_email" name="c_email" />
<label for="password">Password</label>
<input type="password" id="password" name="password" />
<label for="c_password">Retype Password</label>
<input type="password" id="c_password" name="c_password" />
<input type="submit" value="registrati" />
</form>
This is the code that stores data on db:
<?php
function mt_rand_str ($length, $available = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789') {
for ($string = '', $i = 0; $i < $length; ++$i) {
$string .= $available[mt_rand(0, strlen($available)-1)];
}
return $string;
}
include('connection.php');
$con = connection();
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$bonus = 10;
$today = new DateTime();
$signUpDate = $today->format('Y-m-d');
if(strpos($name,' ') !== false) {
echo "
<script>
alert('Nome non valido!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($surname,' ') !== false) {
echo "
<script>
alert('Cognome non valido!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($email,' ') !== false) {
echo "
<script>
alert('Email non valida!');
window.location.href = '../signup.php';
</script>";
exit;
}
if(strpos($password,' ') !== false) {
echo "
<script>
alert('Password non valida!');
window.location.href = '../signup.php';
</script>";
exit;
}
connectionCheck($con);
userDbCheck($con);
$checkEmail = mysqli_query($con,"Select * from Users_DB where email = '$email'");
if(!mysqli_fetch_assoc($checkEmail)) {
do {
$userCode = mt_rand_str(8);
}
while(mysqli_fetch_assoc(mysqli_query($con,"select * from Users_DB where binary UserCode = '$userCode'")));
$value = 20;
mysqli_query($con,"Insert into User_DB (UserCode,Name,Surname,Phone,Email,Password,SignUpDate,bonus)
values ('$userCode','$name','$surname','','$email','$password','$signUpDate','$bonus')");
}
else {
echo "
<script>
alert('Email exists already!');
window.location.href = '../signup.php';
</script>";
}
?>
I hope you can find what I have not. As you can see, I've put in php code some data check too.
So I have
1) HTML5 check: type="email". I'm thinking to put also "pattern match" in all fields
2) JavaScript check
3) PHP check
I'm so desperate...
Thank you before.
I have PHP to validate a form, it echos and error message
<?php
if(!$_POST) exit;
error_reporting(0);
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
$verify = $_POST['verify'];
$nameerror = 'please enter your name';
if(trim($name) == '') {
echo '<div class="error_name">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message"><br /><br /><center>Attention! Please enter a valid email address.</center></div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message"><br /><br /><center>Attention! Please enter a valid phone number.</center></div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message"><br /><br /><center>Attention! Phone number can only contain digits.</center></div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message"><br /><br /><center>Attention! You have enter an invalid e-mail address, try again.</center></div>';
exit();
}
else if(trim($comments) == '') {
echo '<div class="error_message"><br /><br /><center>Attention! Please enter your message.</center></div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "joe.doe#yourdomain.com";
$address = "cedrichugh#yahoo.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name , their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name via email, $email or via phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: Website_Contact_Form" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<center><h1>Email Sent Successfully.</h1></center>";
echo "<center><p>Thank You <strong>$name</strong>, Your Message Has Been Sent. We Will Be In Contact With You Shortly.<br />Med Perfect</p></center>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
But the DIV.error_name displays at the bottom of the page.
How can I append it to the input field so it can be displayed above or below it
<form role="form" id="feedbackForm" method="post" action="index.php?page=contact">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
<span class="help-block" style="display:none;">Please enter your name.</span>
</div>
<div class="form-group">
<input type="phone" class="form-control" id="phone" name="phone" placeholder="Contact Number">
<span class="help-block" style="display: none;">Please enter a valid contact number address.</span>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address">
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<select name="select" class="form-control" id="select">
<option value="">Please Select Your Interest</option>
<option value="general_enquiry">General Enquiry</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="other">Other</option>
</select>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div class="form-group">
<textarea rows="10" cols="100" class="form-control" id="comments" name="comments" placeholder="Message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
<button type="submit" name="submit" id="feedbackSubmit" class="btn44 btn-4 btn-4c icon-mail-send" style="display: block; margin-top: 10px;">Send</button>
</form>
I have tried the following from api.jquery.com(I am a noob)
$( "#name" ).append( ".error_name" );
Create a JavaScript function that handles the updating of the DOM with the error message, and the function can be called from anywhere on the page. You'll be able to trigger the error messages wherever you want, including the HTML file, the JavaScript file, or on the PHP side.
Sample JS function:
function displayError(fieldID, errorClass, errorMessage) {
if ($('#' + fieldID).next('.' + errorClass).length == 0) {
$('#' + fieldID).after('<div class="' + errorClass + '">' + errorMessage + '</div>');
}
}
To call the JavaScript function (DOM must be ready):
displayError('name', 'error_name', 'You must enter your name.');
To control the calling of the function from PHP in your server-side validation:
if(trim($name) == '') {
// Call error message function after when DOM is ready
echo '<script>$(function () { displayError(\'name\', \'error_name\', \'You must enter your name.\'); });</script>';
exit();
}
You could also use the same function when validating on the JavaScript side:
$(function () {
$('#btnSubmit').on('click', function () {
event.preventDefault;
// Validate
if ($('#name').val() == '') {
// Name field is empty
displayError('name', 'error_name', 'You must enter your name.');
}
});
});
Demo: https://jsfiddle.net/BenjaminRay/6cLvnk3L/
How do you add the div to your site?
List of thoughts in order of preference.
You could leave an empty div (<div class"error_name"></div>) where you want the message to appear and add returned text to it (without the surrounding tags).
Instead of appending a string ".error_name", add the result of $(".error_name"). So $( "#name" ).after( $(".error_name") ); if the div is already added to the DOM. .append() adds it as a child of input.
You can also style and position the div with jquery and css without worrying about it's placement in DOM.
I have a contact form where the user inputs his name, designation, message etc and is validated using a javascript file called screen.js.
This is my code in the contact form in html view.
<div class="contact_us">
<form id="contactform" action="#" method="post">
<div class="formpart">
<label for="contact_name">Name</label>
<p><input type="text" name="name" id="contact_name" value="" class="requiredfield"/></p>
</div>
<div class="formpart formpart1">
<label for="contact_designation">Designation</label>
<p><input type="text" name="designation" id="contact_designation" value=""/></p>
</div>
<div class="formpart">
<label for="contact_companyname">Company Name</label>
<p><input type="text" name="companyname" id="contact_companyname" value="" class="requiredfield"/></p>
</div>
<div class="formpart formpart1">
<label for="contact_email">Email Address</label>
<p><input type="text" name="email" id="contact_email" value="" class="requiredfield"/></p>
</div>
<div class="formpart">
<label for="contact_phone">Contact No.</label>
<p><input type="text" name="phone" id="contact_phone" value=""/></p>
</div>
<div class="formpart">
<label for="contact_message">Message</label>
<p><textarea name="message" id="contact_message" class="requiredfield"></textarea></p>
</div>
<div class="formpart">
<button type="submit" name="send" class="sendmessage">Send</button>
</div>
<div class="formpart">
<span class="errormessage">Error! Please correct marked fields.</span>
<span class="successmessage">Email send successfully!</span>
<span class="sendingmessage">Sending...</span>
</div>
</form>
</div>
and the javascript file screen.js contains
jQuery(document).ready(function() {
/* Contact Form */
if(jQuery('#contactform').length != 0){
addForm('#contactform');
}
/* Newsletter Subscription */
if(jQuery('#newsletterform').length != 0){
addForm('#newsletterform');
}
});
/* Contact Form */
function addForm(formtype) {
var formid = jQuery(formtype);
var emailsend = false;
formid.find("button[name=send]").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(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 () {
jQuery(this).val("");
})
formid.find("textarea").val("");
emailsend = false;
}
function sendemail() {
formid.find(".successmessage").hide();
var phpfile = "";
if(formtype=="#contactform"){
phpfile = "../php/contact.php";
}else if(formtype=="#newsletterform"){
phpfile = "php/signup.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();
resetform();
});
}
}
return false
}
}
and my php file contact.php
<?php
$to = "developer#vakilspremedia.com"; /* Enter your email adress here */
$name = trim($_POST['name']);
$designation = trim($_POST['designation']);
$companyname = trim($_POST['companyname']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$message = str_replace(chr(10), "<br>", $_POST['message']);
$body = "<html><head><title>Contact Form Email</title></head><body><br>";
$body .= "Name: <b>" . $name . "</b><br>";
$body .= "Designation: <b>" . $designation . "</b><br>";
$body .= "Company Name: <b>" . $companyname . "</b><br>";
$body .= "Email: <b>" . $email . "</b><br>";
$body .= "Phone: <b>" . $phone . "</b><br><br>";
$body .= "Message:<br><hr><br><b>" . $message . "</b><br>";
$body .= "<br></body></html>";
$subject = 'Contact Form Email from ' . $name;
$header = "From: $to\n" . "MIME-Version: 1.0\n" . "Content-type: text/html; charset=utf-8\n";
mail($to, $subject, $body, $header);
?>
The validation works perfect but when I enter values in all field it shows sending... as the message and doesn't show Email successfully sent at all even after hours and hours of waiting. It seems it does nothing after I click on send button.
Modify ur js for this code make sure phpfile var have url path or put contact.php in same directory
jQuery.post('contact.php', formid.serialize(), function() {
console.log('success');
formid.find(".sendingmessage").hide();
formid.find(".successmessage").fadeIn();
resetform();
});