Contact Forms + PHP + Validation - javascript

I'm trying to get my simple contact form to be functional. I want this form to either email me or record the contact data somewhere. I'm just now starting to learn PHP and Javascript -- so my knowledge is extremely limited.
The validation seems to be working (it will alert you if you don't put in a valid email, for example) -- but the form itself isn't being submitted anywhere.
When you enter information and click submit you'll get an ERROR 404 - Not Found (Then it references contact.php -- the php file I'm using) How can I start to troubleshoot this? Furthermore, if you have a clear, simple resource for learning about PHP and forms then I'd be more than happy to study more. I've searched (for a few hours) for decent tutorials but most don't provide clear explanations -- and just encourage you to copy and paste code.
<form role="form" id="contactform" form action="contact.php" method="post">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="subject" class="form-control" id="subject">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" rows="3"></textarea>
</div>
<button type="submit" class="btn">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div>
</form>
---PHP---
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$EmailTo = "william#whatsauce.com";
$Subject = "New Message Received";
// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .="Subject: ";
$Body .= $subject;
$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";
}
?>

Use a name attribute in your input fields. Only then you will be able to capture them values in your $_POST as a valid index, not through ids.

Related

PHP Notice: Undefined index: Name in {project Folder}/contact/contactengine.php on line 6

I hope that you can help me with a problem that I have. I have a contact form, and I am getting an error log like this:
PHP Notice: Undefined index: Name in {path}/contactengine.php on line 6
PHP Notice: Undefined index: Email in {path}/contactengine.php on line 7
PHP Notice: Undefined index: Message in {path}/contactengine.php on line 8
my PHP code and HTML are:
<?php
$EmailFrom = "";
$EmailTo = "admin#memwdesings.com";
$Subject = "From website";
$Name = Trim(stripslashes($_POST['Name'])); // line 6
$Email = Trim(stripslashes($_POST['Email'])); // line 7
$Message = Trim(stripslashes($_POST['Message']));// line 8
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$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: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://arquitectura-om.com/\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
<!-- Contact Form -->
<div class="col-md-5">
<div class="contact-header">Send us a Message</div>
<form method="post" action="contact/contactengine.php">
<div class="control-group form-group">
<div class="controls">
<label>Name:</label>
<input type="text" class="form-control" id="Name" required data-validation-required-message="Please enter your name.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Email:</label>
<input type="email" class="form-control" id="Email" required data-validation-required-message="Please enter your email address.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Message:</label>
<textarea rows="10" cols="100" class="form-control" id="Message" required data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="contact-btn btn">Send Message</button>
</form>
</div>
No name attributes in your form fields means no values submitted.
id attributes don't count.
Basically, if you don't need the id attribute for css, js, or the labels, just replace id with name.
Give your submit button a name submit and put all php code inside a if condition in contactengine.php file like
if(isset($_POST['submit'])){
print_r($_POST);
}
Hi you have not given the name attribute of form elements submitted.
You have to give name of each form element and then use that name to get values in submitted action of form like in $_POST['name']

Contact form is sending email but not responding after submission.

I have my contact form set where after submitting it redirects back to my homepage but for some reason it just stays on the same page. I'm trying to receive confirmation after email is sent and then a redirect back to my homepage. I'm using php and javascript...........................................
<div class="col-sm-6 col-sm-offset-3">
<h3>Send me a message</h3>
<form role="form" id="contactForm" action="index2.php" method="POST">
<div class="row">
<div class="form-group col-sm-6">
<label for="name" class="h4">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name" required>
</div>
<div class="form-group col-sm-6">
<label for="email" class="h4">Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" required>
</div>
</div>
<div class="form-group">
<label for="message" class="h4 ">Message</label>
<textarea id="message" class="form-control" rows="5"
placeholder="Enter your message" required></textarea>
</div>
<button type="submit" id="form-submit" class="btn btn-primary btn-lg
pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div>
</form>
index2.php
<meta http-equiv="refresh" content="0; url=http://myurl.com/" />
</header>
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "arash281pro#live.com";
$Subject = "New Message Received";
// 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";
}
?>
js
$("#contactForm").submit(function(event){
// cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "index2.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
function formSuccess(){
$( "#msgSubmit" ).removeClass( "hidden" );
}
var confirmSubmit = true;
$('form').submit(function(e) {
if (confirmSubmit) {
e.stopPropagation();
if (confirm('Are you sure you want to send this form?')) {
confirmSubmit = false;
$('form').submit();
}else{
alert("The form was not submitted.");
}
}
});
You're not actually redirecting back to your homepage.
For that you'll need to add something like this after your submit function:
window.location.replace("index2.php");
Rather than using <meta http-equiv="refresh" content="0; url=http://myurl.com/" /> in index2.php, just add header("Location: http://myurl.com/"); at the end of the script instead of "success" or "invalid" message. Also remove any HTML before the PHP code starts to prevent errors like "Headers already sent, output started on line ..."

PHP Contact form submits without needing all fields filled in

I have a PHP contact form which works even if the fields are not filled in. This hasn't been a problem until recently when I've started to get handfuls of blank emails every day.
How do enforce all fields to be filled out in the form before the submit button can be used?
Here is my PHP code below:
<?php
header("Access-Control-Allow-Origin: *");
$EmailFrom = "myemail";
$EmailTo = "myemail";
$Subject = "subject goes here";
$Email = Trim(stripslashes($_POST['email']));
$Message = Trim(stripslashes($_POST['message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom" . "\r\n" );
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
And here is my HTML markup:
<!-- CONTACT FORM -->
<div class="span9 contact_form">
<div id="note"></div>
<div id="fields">
<div id="post-ajax" style="display: none;"></div>
<form id="contact-form-face" class="clearfix" action="/php/contactengine.php">
<input type="text" name="email" value="Email" onFocus="if (this.value == 'Email') this.value = '';" onBlur="if (this.value == '') this.value = 'Email';" />
<textarea name="message" onFocus="if (this.value == 'Message') this.value = '';" onBlur="if (this.value == '') this.value = 'Message';">Message</textarea>
<input class="contact_btn" name="submit" type="submit" value="Send Message" />
</form>
</div>
</div>
<!-- //CONTACT FORM -->
I can't find your fields. But in general, HTML5 provides a very convenient way to make a form field required. To do so, you can add a required attribute in your form elements, such as:
<input type="text" name="txt_name" required />
Modern browsers will validate the fields during form submit. To support older browsers, you can use JS validation libraries for client-side validation and use PHP condition check, e.g. if(!empty($_POST['txt_name'])) for server-side validation.
Moreover, it is suggested not to use meta refresh tag for redirection; use header('Location: error.htm'); exit; for example, instead.
<!-- CONTACT FORM -->
<div class="span9 contact_form">
<div id="note"></div>
<div id="fields">
<div id="post-ajax" style="display: none;"></div>
<form id="contact-form-face" class="clearfix" action="/php/contactengine.php">
<input type="text" name="email" value="Email" onFocus="if (this.value == 'Email') this.value = '';" onBlur="if (this.value == '') this.value = 'Email';" required />
<textarea name="message" onFocus="if (this.value == 'Message') this.value = '';" onBlur="if (this.value == '') this.value = 'Message';" required>Message</textarea>
<input class="contact_btn" name="submit" type="submit" value="Send Message" />
</form>
</div>
</div>
<!-- //CONTACT FORM -->
Apart from adding the required attribute as indicated in the other answer(which can be by passed very easy through inspect element) you also need validation in the server side as well before processing.
You can create an array of the required fields then check, if those fields are set and not empty.
<?php
$errors = "";
$requiredFields = array("email","message"); // enter the name in the inputs, ie name="someInput"
foreach($requiredFields as $fieldname){
if(!isset($_POST[$fieldname]) && empty($_POST[$fieldname])){
$errors++;
echo "Enter all fields";
//OR redirect to error page
}
}
if($errors <=0){
// Proccess the form
$EmailFrom = "myemail";
$EmailTo = "myemail";
$Subject = "subject goes here";
$Email = Trim(stripslashes($_POST['email']));
$Message = Trim(stripslashes($_POST['message']));
// prepare email body text
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom" . "\r\n" );
// redirect to success page
if ($success){
header("location:contactthanks.php");
exit();
}
else{
header("location:error.htm")
exit();
}
}
?>

Get input value and show it in new page after submit

I tried to show user input after they submit their form.
Here is the form looks like:
<form class="form-horizontal col-sm-12" name="enq" method="post" action="email/" >
<div class="form-group"><label>Name</label><input class="form-control required" name="name" placeholder="Your name" data-placement="top" data-trigger="manual" data-content="Must be at least 3 characters long, and must only contain letters." type="text"></div>
<div class="form-group"><label>Message</label><textarea class="form-control" name="message" placeholder="Your message here.." data-placement="top" data-trigger="manual"></textarea></div>
<div class="form-group"><label>E-Mail</label><input class="form-control email" name="email" placeholder="email#you.com (so that we can contact you)" data-placement="top" data-trigger="manual" data-content="Must be a valid e-mail address (user#gmail.com)" type="text"></div>
<div class="form-group"><label>Phone</label><input class="form-control phone" placeholder="999-999-9999" data-placement="top" data-trigger="manual" data-content="Must be a valid phone number (999-999-9999)" type="text"></div>
<div class="form-group"><input type="submit" class="btn btn-success pull-right" id="submit" name="submit"></input> <p class="help-block pull-left text-danger hide" id="form-error"> The form is not valid. </p></div>
</form>
Here is the PHP after the user submit:
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="test#ymail.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../success.php");
else
header("Location:../test.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
And here is success.php:
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<strong>Name:</strong> ".$name."<br>";
echo "<strong>Email:</strong> ".$email."<br>";
echo "<strong>Message:</strong> ".$query."<br>";
I could receive what the user sent in my email, but the problem is with success.php, I tried to use the above code, but what I got is undefined index.
Is there a way to show the input values in the new page after submit?
Use session variables or you could alternatively send the data through the URL and use $_GET on the success page (I probably don't suggest this though).
PHP after submit:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="test#ymail.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
{
session_start();//Start the session
$_SESSION['name'] = $name; //Set name session
$_SESSION['email'] = $email; //Set email session
$_SESSION['query'] = $query; // Set query session
header("Location:../success.php");
}
else
{
header("Location:../test.php?msg=Error To send Email !");
}
}
?>
success.php
<?php
session_start();
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>";
echo "<strong>Name:</strong> ".$_SESSION['name']."<br>";//Use the session variables
echo "<strong>Email:</strong> ".$_SESSION['email']."<br>";
echo "<strong>Message:</strong> ".$_SESSION['query']."<br>";
?>
It essentially saves the data into variables that will work whenever sessions are started on alternative pages and can be called using $_SESSION.
You are redirecting to another page so the post values are not passed to the success page. What you could do it put them temporairy in a session

PHP contact form will just refresh the page after submission.

After searching for about 3 hours i still can't figure this one out.
I Have a html template with a contact form and im trying to make it work using a PHP script.
I changed the template to PHP and pasted the PHP form script in it. everything is working fine except the confirmation text.
After a successful submission it will just refresh the page instead of printing "Your mail has been sent successfuly ! Thank you for your feedback". i do not want a redirect, i just want it to print on the same page.
Any ideas?
I got a sample of my code.
<form action="<? echo $_SERVER['PHP_SELF']; ?>" id="contact-form" method="post" class="form afsana-form" role="form">
<div class="row">
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="name" name="name" placeholder="name" type="text" required autofocus />
</div>
<div class="col-sm-12 form-group">
<input class="form-control afsana-style" id="email" name="email" placeholder="email" type="email" required />
</div>
<div class="col-sm-12 form-group">
<textarea class="form-control" id="message" name="message" placeholder="message" rows="5"></textarea>
</div>
<div class="col-sm-12 form-group">
<button class="btn btn-primary afsana-btn" name="submit" value="verzenden" type="submit">Verzenden <i class="ion-arrow-graph-up-right"></i></button>
</div>
</div>
</form>
<?php
if(isset($_POST["submit"])){
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["email"]==""||$_POST["message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$subject = (Contact_form);
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$headers .= 'Cc:'. $email2 . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("something#domain.com", $subject, $message, $headers);
echo "Your mail has been sent successfuly ! Thank you for your feedback";
}
}
}
?>
First, you have this: $subject = (Contact_form); which should throw an error, so I assume you have error reporting turned off. When developing, you should have error reporting on so you can see errors in your code... Else you are just working blind. I don't mean by throwing tacky error_reporting(0) in every file either, I mean to set your error reporting level to E_ALL in your php.ini.
You also have: $headers .= 'Cc:'. $email2 . "\r\n";
However, $email2 is not defined anywhere, so you would get an error here too.. which is why it's important to test with error reporting on.
See if this works:
<?php
$error = '';
if(isset($_POST['submit']))
{
if ( !empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']) )
{
$email = $_POST['email'];
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( $email = filter_var($email, FILTER_VALIDATE_EMAIL) )
{
$subject = '(Contact_form)';
$message = $_POST['message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
$message = wordwrap($message, 70);
if ( $result = mail("something#domain.com", $subject, $message, $headers) ) {
$error = 'Success';
} else {
$error = 'There was an error sending your email!';
}
} else {
$error = 'Invalid Email Address!';
}
} else {
$error = 'Please fill all fields.';
}
}
?>
<p><?= $error ?></p>
<form action="" method="post">
<input type="text" name="name" value="" /><br />
<input type="email" name="email" value="" /><br />
<textarea name="message" rows="5"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
Try to put in $subject just a string value like:
$subject = 'Test subject';
change also the following line to this (there is no $email2 defined):
$headers .= 'Cc:'. $email . "\r\n"; // Carbon copy to Sender
and give it a try. You can also put as first line of your code
<?php error_reporting(E_ALL); ?>
and check for errors when submiting the form.

Categories

Resources