Im trying to create ajax from with php validation, let explain with screenshot. while validating form im getting all error in same place…
what im trying to get is individual validation for field like below
And after form is submitted i want display success message at the top of form but im getting success message on all field
html form data (index.php)
<form id="first_form" method="POST" action="form.php">
<p class="form-message"></p>
<div class="mb-3">
<input type="text" class="form-control" id="name" name="name" placeholder="Name:">
<p class="form-message"></p>
</div>
<div class="mb-3">
<input type="tex" class="form-control" id="email" name="email" placeholder="Email:">
<p class="form-message"></p>
</div>
<div class="mb-3">
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="address" name="address" placeholder="Address:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="services" name="services" placeholder="Services:">
</div>
<div class="mb-3">
<textarea class="form-control" rows="5" id="message" name="message" placeholder="Leave Your Message..."></textarea>
</div>
<button type="submit" name="submit" id="submit" class="btn btn-primary">Submit</button>
js code:
$(document).ready(function() {
$("#first_form").submit(function(event) {
event.preventDefault();
name = $("#name").val();
email = $("#email").val();
phone = $("#phone").val();
address = $("#address").val();
subject = $("#subject").val();
services = $("#services").val();
message = $("#message").val();
submit = $("#submit").val();
$(".form-message").load("form.php", {
name: name,
email: email,
phone: phone,
address: address,
subject: subject,
services: services,
message: message,
submit: 'submitted'
});
});
});
form.php data
if (isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = "Contact Form";
$mailTo = "hello#develoweb.com";
$headers = "From: ".$email;
$txt = "You have received a message from ".$name.
".\n\n".$message;
$errorEmptyname = false;
$errorEmptyemail = false;
$errorEmptymessage = false;
$errorEmail = false;
if (empty($name)) {
echo "<span class='form-error'>Name Field cannot be empty</span> ";
//$errorEmptyName = true;
}
if (empty($email)) {
echo "<span class='form-error'>Email Field cannot be empty</span>";
//$errorEmptyemail = true;
}
if (empty($message)) {
//$errorEmptymessage = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>
Write a valid e-mail addres </span>";
$errorEmail = true;
}
else {
echo "<span class='form-success'>
Thank you for your message!<br>
I'll get back to you as soon as I can.</span>";
mail($mailTo, $subject, $body, $headers);
}
}
else{
echo "There was an error!";
}
what i have understand, im not getting individual validation error in individual field bcz class is same, how can i append error to related fields
i havent used js validation bcz i want to some validation for spammer to prevent spam mail and as we know while viewing source code we can easily view code for validation too, so pefer validation in php
Related
I have a php simple project.
The project is to create an email submission page.
I use phpstorm software.
<?php
//get user input
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
//error message
$missingName = '<p><strong>Please enter your name</strong></p>';
$missingEmail = '<p><strong>Please enter your email address</strong></p>';
$invalidEmail = '<p><strong>Please enter a valid email address</strong></p>';
$missingMessage = '<p><strong>Please enter a message</strong></p>';
//if the user has submitted the form
if ($_POST["submit"]){
//check for errors
if (!$name){
$errors .= $missingName;
}else{
filter_var($name, FILTER_SANITIZE_STRING);
}
if (!$email){
$errors .= $missingEmail;
}else{
filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($invalidEmail, FILTER_VALIDATE_EMAIL)){
$errors .= $invalidEmail;
}
}
if (!$message){
$errors .= $missingMessage;
}else{
$message = filter_var($message, FILTER_SANITIZE_STRING);
}
//if there are any errors
if ($errors){
$resultMessage = '<div class="alert alert-danger">' . $errors . '</div>';
}
}
?>
<form action="index.php" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" placeholder="Name" id="name" class="form-control">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" name="email" placeholder="Email" id="email" class="form-control">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea name="message" id="message" class="form-control" rows="5"></textarea>
</div>
<input type="submit" name="submit" id="submit" class="btn btn-success btn-lg" value="Send Message">
</form>
When I run the project, I encounter the errors you see in the image
error messages
Errors are from the following lines
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
And this line
if ($_POST["submit"])
please help!
Before accessing POST variable you should check if its not empty:
if(isset($_POST['submit']){
//your code
}
I am buidling a php contact form with ajax validation. While I submit the contact form I get error message "spammer" which is not supposed to.
Below is my code html & php code.
Index.php
<form id="contactform" method="post" action="mailer.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="username" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" class="form-control" id="phone" name="phone" placeholder="Enter your phone number">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email address">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" name="message" rows="4" placeholder="Enter your email message"></textarea>
</div>
<br>
<div class="g-recaptcha" data-sitekey="6Lct9zUUAAAAABpj9vwKX9B7x_AH8s9gwJzFW1sB"></div>
<br>
<div id="formresult">
</div>
<button type="submit" name="submit" class="btn btn-info">Submit</button>
</form>
Mailer.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["username"]);
$phone = trim($_POST["phone"]);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if(isset($_POST['g-recaptcha-response'])){
$captcha = $_POST['g-recaptcha-response'];
}
//Validate the data
if (empty($name) OR empty($phone) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($message) OR empty($captcha)) {
http_response_code(400);
echo "<span class='glyphicon glyphicon-remove' aria-hidden='true'></span> <strong>Please fill all the form inputs and check the captcha to submit.</strong>";
exit;
}
//recipient email address.
$recipient = "abc#abc.com";
$subject = "New message from $name";
//email content.
$email_content = "Name: $name\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
//email headers
$email_headers = "From: $name <$email>";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR_SECRATE_KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$decoded_response = json_decode($response, true);
if($decoded_response['success'] == true){
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "<span class='glyphicon glyphicon-ok' aria-hidden='true'></span> <strong>Thank You! Your message has been sent.</strong>";
} else {
http_response_code(500);
echo "Your message cannot be sent";
}
} else {
http_response_code(400);
echo 'spammer!';
}
}
?>
When I submit the form I get a error message 'spammer' and even mail does not get through.
I know there is some mistake in logic but i cannot figure it out.
Anyone please help me in this. Thank you.
The line of code:
if($decoded_response['success'] == true){
Must be evaluating to false, and executing the else part of that statement. Displaying the spammer message.
Check the decoded contents returned from the recaptcha url, that you assign to the $decoded_response variable.
print_r($decoded_response); // should show the whole contents
Straight to the point. I'm trying to set up a contact form on my website but struggling to make it work. Also have read through numerous of related topics here on SO. I followed tutorial thus I've got decent familiarity with this topic. I'm sure my php.ini file is configured just fine since sending emails worked until recently (although it always ended up in junk mail). Until I made changes to the code. Changes that I needed to make sooner or later. Strangely, sending emails worked when I ran it with hard-coded details with no variables. But when I implemented variables then it stopped working. Obviously I need PHP to process user's input through variables. How can get PHP to read user's input ? I think the most important part is using the attribute name="something" in input tags.
Sharing relevant code:
PHP:
<?php
$fullName = $errorMsg = $sucMsg = "";
$errMsg = $email = $subject = $emailErr = $message = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit'])) {
$fullName = test_input($_POST['fullName']);
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Your email address is not valid !";
} else {
$email = $_POST['email'];
}
$subject = test_input($_POST['subject']);
$message = test_input($_POST['message']);
if($emailErr == "") {
$emailTo = "mark.alexa.uk#gmail.com";
$headers = "From ".$fullName." ".$email." via contact form";
$headers .= "Reply-To: ".$email;
$headers .= "Return-Path: webmaster#ubuntuserver\r\n";
$headers .= "CC: alexa.mark#mail.com\r\n";
$headers .= "BCC: alexa.mark#mail.com\r\n";
if (mail($emailTo, $subject, $message, $headers)) {
$sucMsg = "<p>The email was sent successfully !</p>";
} else {
$errMsg = "<p>The email could not be sent !</p>";
}
}
}
?>
HTML:
<div class="container" id="form">
<div id="successMsg" class="alert alert-success" role="alert"><?php
echo $sucMsg; ?></div>
<div id="errMsg" class="alert alert-danger" role="alert"><?php echo
$errMsg; ?></div>
<form method="POST" action="contact.php">
<fieldset class="form-group">
<label for="fullName">Full name</label>
<input type="text" class="form-control" name="fullName"
id="fullName" placeholder="full name" required>
</fieldset>
<fieldset class="form-group">
<label for="email">Email</label>
<input type="email" id="email" placeholder="email" class="form-
control" required>
<small id="emailHelp" name="email" class="form-text text-muted">I
won't share your email with anyone</small>
</fieldset>
<fieldset class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" name="subject" id="subject" placeholder="subject" required>
</fieldset>
<fieldset class="form-group">
<label for="message">Your message</label>
<input type="text" class="form-control" name="message" id="message" placeholder="message" required>
<input type="submit" id="submit" class="btn btn-success" value="Submit">
</fieldset>
</form>
</div>
UPDATE:
How should I modify the PHP code so it won't end up in junk mail ?
Add name="submit" to your submit button. Forms pass on the name attribute to the post array. So your code test for:
if (isset(`$_POST['submit']`)) {
$fullName = test_input($_POST['fullName']);
..isn't valid because $_POST['submit'] isn't set.
<input type="submit" id="submit" name="submit" class="btn btn-success" value="Submit">
I have a problem with checking if a email is valid. but the weird is that i have the same form on to different pages/urls, and on one of the forms it keeps saying that the email is invalid and on the form its valid.
The form on this page works - http://night.sendme.to/about
the form on this page doesnt - http://night.sendme.to/book/jokeren
The HTML on the forms is the same
<form action="" method="post" id="myform">
<div class="form-group">
<label for="name">Navn *</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Navn" required="required">
</div>
<div class="form-group">
<label for="corp">Virksomhed</label>
<input type="text" class="form-control" id="corp" name="corp" placeholder="Virksomhed">
</div>
<div class="form-group">
<label for="email">Email adresse *</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email adresse" required="required">
</div>
<div class="form-group">
<label for="tel">Telefon *</label>
<input type="tel" class="form-control" id="tel" name="tel" placeholder="Telefon" required="required">
</div>
<div class="form-group">
<label for="message">Kommentar</label>
<textarea class="form-control" id="message" name="message" rows="10" required="required"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit">Send</button>
</form>
<div id="success" style="color:red;"></div>
The PHP is this
<?php // Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'YOURMAIL';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$header .= "from:".$_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $header); //This method sends the mail.
echo "Your email was sent!";
echo var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
} else {
echo "Invalid Email, please provide an correct email.";
echo var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>
The javascript is this
$(document).ready(function(){
$('#submit').click(function(){
$.post("email.php", $("#myform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
Hope some one can help, why the form only works on the http://night.sendme.to/about and the others
So, to not leave this question answer-less:
In your HTML code, you actually had <form action="" method="post" id="myform"> in both pages – but in your second page, you had another <form> tag right before it … and because of this invalid HTML, the browser ignored the second form tag, and that made $("#myform").serialize() not return any data at all, because it could not find the form element with that id.
You should always validate your HTML code. This helps avoiding such errors.
I have a simple php contact form i got from a web tutorial. It worked yesterday, but will not work today. I'd love some help, as I don;t know much php.
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 (!filter_var( trim($_POST['email'], FILTER_VALIDATE_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 = 'person#domain.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;
}
}
?>
HTML:
<form role="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<?php if(isset($hasError)) { //If errors are found ?>
<p class="alert alert-danger">Please check if you've filled all the fields with valid information and try again. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<div class="alert alert-success">
<p><strong>Message Successfully Sent!</strong></p>
<p>Thank you for using our contact form, <strong><?php echo $name;?></strong>! Your email was successfully sent and we’ll be in touch with you soon.</p>
</div>
<?php } ?>
<div class="form-group">
<label for="name">Your Name<span class="help-required">*</span></label>
<input type="text" name="contactname" id="contactname" value="" class="form-control required" role="input" aria-required="true" />
</div>
<div class="form-group">
<label for="email">Your Email<span class="help-required">*</span></label>
<input type="text" name="email" id="email" value="" class="form-control required email" role="input" aria-required="true" />
</div>
<div class="form-group">
<label for="subject">Subject<span class="help-required">*</span></label>
<input type="text" name="email" id="subject" class="form-control required" role="input" aria-required="true">
</div>
<div class="form-group">
<label for="message">Message<span class="help-required">*</span></label>
<textarea rows="8" name="message" id="message" class="form-control required" role="textbox" aria-required="true"></textarea>
</div>
<div class="actions">
<input type="submit" value="Send Your Message" name="submit" id="submitButton" class="btn btn-grey" title="Click here to submit your message!" />
<input type="reset" value="Clear Form" class="btn btn-grey pull-right" title="Remove all the data from the form." />
</div>
</form>
It gets hung up on the validation. Not sure why.
$_POST["subject] is not defined in your form. Your SUBJECT field is called EMAIL:
Change:
<div class="form-group">
<label for="subject">Subject<span class="help-required">*</span></label>
<input type="text" name="email" id="subject" class="form-control required" role="input" aria-required="true">
</div>
With:
<div class="form-group">
<label for="subject">Subject<span class="help-required">*</span></label>
<input type="text" name="subject" id="subject" class="form-control required" role="input" aria-required="true">
</div>