The code of the contact form below gives me an error FORM SENDING FAILED.
Can you please help me resolve the issue?The code of the contact form below gives me an error FORM SENDING FAILED.
Can you please help me resolve the issue?The code of the contact form below gives me an error FORM SENDING FAILED.
Can you please help me resolve the issue?
<form id="contactform" method="post" action="$_SELF">
<label class="hide" for="author">Full Name</label>
<input class="input-fields" id="author" name="name" type="text" placeholder="Full Name" value="" required autofocus />
<label class="hide" for="email">Email</label>
<input class="input-fields" id="email" name="email" type="text" placeholder="Email Address" value="" autofocus />
<label class="hide" for="email">Mobile No</label>
<input class="input-fields" id="email" name="phone_no" type="text" placeholder="Mobile No" value="" autofocus />
<label class="hide" for="author">Company</label>
<input class="input-fields" id="author" name="company" type="text" placeholder="Company" value="" required autofocus />
<label class="hide" for="select_category">Select a Industry:</label>
<span id="select_group" class="select-group">
<select name="vehicle">
<option value="General" >Select a Industry:</option>
<option value="General" >Health Centres Hospitals</option>
<option value="Sales" >Tradeshows Conferences</option>
<option value="Support" >Fast Foods and Restaurants</option>
<option value="Support" >Night CLub, Bars and Disos</option>
<option value="Support" >Banks , Rent Estate</option>
<option value="Support" >Educational Institute</option>
<option value="Support" >Recreational Facilities</option>
<option value="Support" >Malls,Luxury Retail and Store Windows</option>
</select>
</span>
<label class="hide" for="subject_title">Solutions</label>
<input class="input-fields" id="subject_title" name="solution" type="text" placeholder="Solutions" value="" autofocus />
<label class="hide" for="author">Require</label>
<input class="input-fields" id="author" name="require" type="text" placeholder="Require" value="" required autofocus />
<label class="hide" for="comment">Message</label>
<textarea id="comment" class="input-fields" placeholder="Message" name="message" cols="40" rows="200"></textarea>
<span class="form_response">
<ul id="errors" class="">
<li id="info">There were some problems with your form submission:</li>
</ul>
<p id="success" class="">Thanks for your message! We will get back to you ASAP!</p>
</span>
<input name="submit" type="submit" id="submit-contact-info" class="contact-info-submit form-submit-button span2" value="Send message">
</form>
</div>
</div>
</article>
</main>
</div>
<?php
//If the form is submitted
echo "hello";
if(isset($_REQUEST['submit']))
{
$message = $_POST['message'];
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['vehicle']) == '') {
$hasError = true;
} else {
$vehicle = trim($_POST['vehicle']);
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['require']) == '') {
$hasError = true;
} else {
$require = trim($_POST['require']);
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['solution']) == '') {
$hasError = true;
} else {
$solution = trim($_POST['solution']);
}
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = true;
} else {
$name = trim($_POST['name']);
}
//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 that the mobile no field is not empty
if(trim($_POST['phone_no']) == '') {
$hasError = true;
} else {
$phone_no = trim($_POST['phone_no']);
}
//If there is no error, send the email
if(!isset($hasError))
{
$emailTo = "sahil7771#gmail.com"; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nMobile No: $phone_no \n\n Your Industry: $vehicle \n\
\n\n Your Requirement: $require \n\n Your Solution: $solution \n\n
\n\n Message : $message
\n\nPlease Contact $name on $phone_no\n \n /====================================/ ";
$headers = 'From: Touch Active <'. $emailTo .'>' . "\r\n" . 'Reply-To: ' . $email;
if(mail($emailTo, 'Mail From Touch Active', $body, $headers))
{ //Replace Your Website Subject
$response=1;
$emailSent = true;
?>
<div id="responsive-container" ><p>Thanks For Messaging Us You Will Shortly Expect Our Assistance ( With In 24hrs ).</p></div>
<?php
}
else
{
?>
<div id="page-title"><h2>Failed To Sent</h2></div>
<?php
$response=0;
}
}
?>
Change in form action="$_SELF" to action="$_SERVER['PHP_SELF']", because there isn't constant like $_SELF.
Actually its working here with no errors
try it with this little script, to check or e-mail is permitted :
<?php
$to = "somebody#example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster#example.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$txt,$headers);
?>
I have tested your script with minor adjustment:
<form id="contactform" method="post" action="#">
<label class="hide" for="author">Full Name</label>
<input class="input-fields" id="author" name="name" type="text" placeholder="Full Name" value="aaa" required autofocus />
<label class="hide" for="email">Email</label>
<input class="input-fields" id="email" name="email" type="text" placeholder="Email Address" value="xxx#boboba.com" autofocus />
<label class="hide" for="email">Mobile No</label>
<input class="input-fields" id="email" name="phone_no" type="text" placeholder="Mobile No" value="0322233355" autofocus />
<label class="hide" for="author">Company</label>
<input class="input-fields" id="author" name="company" type="text" placeholder="Company" value="aaa" required autofocus />
<label class="hide" for="select_category">Select a Industry:</label>
<span id="select_group" class="select-group">
<select name="vehicle">
<option value="General" >Select a Industry:</option>
<option value="General" >Health Centres Hospitals</option>
<option value="Sales" >Tradeshows Conferences</option>
<option value="Support" >Fast Foods and Restaurants</option>
<option value="Support" >Night CLub, Bars and Disos</option>
<option value="Support" >Banks , Rent Estate</option>
<option value="Support" >Educational Institute</option>
<option value="Support" >Recreational Facilities</option>
<option value="Support" >Malls,Luxury Retail and Store Windows</option>
</select>
</span>
<label class="hide" for="subject_title">Solutions</label>
<input class="input-fields" id="subject_title" name="solution" type="text" placeholder="Solutions" value="aaa" autofocus />
<label class="hide" for="author">Require</label>
<input class="input-fields" id="author" name="require" type="text" placeholder="Require" value="aaa" required autofocus />
<label class="hide" for="comment">Message</label>
<textarea id="comment" class="input-fields" placeholder="Message" name="message" cols="40" rows="20"></textarea>
<span class="form_response">
<ul id="errors" class="">
<li id="info">There were some problems with your form submission:</li>
</ul>
<p id="success" class="">Thanks for your message! We will get back to you ASAP!</p>
</span>
<input name="submit" type="submit" id="submit-contact-info" class="contact-info-submit form-submit-button span2" value="Send message">
</form>
</div>
</div>
</article>
</main>
</div>
<?php
//If the form is submitted
if(isset($_REQUEST['submit']))
{
$message = $_POST['message'];
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['vehicle']) == '') {
$hasError = "1";
} else {
$vehicle = trim($_POST['vehicle']);
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['require']) == '') {
$hasError = "2";
} else {
$require = trim($_POST['require']);
}
//Check to make sure that the exit date field is not empty
if(trim($_POST['solution']) == '') {
$hasError = "3";
} else {
$solution = trim($_POST['solution']);
}
//Check to make sure that the name field is not empty
if(trim($_POST['name']) == '') {
$hasError = "4";
} else {
$name = trim($_POST['name']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = "5";
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = "6";
} else {
$email = trim($_POST['email']);
}
//Check to make sure that the mobile no field is not empty
if(trim($_POST['phone_no']) == '') {
$hasError = "7";
} else {
$phone_no = trim($_POST['phone_no']);
}
//If there is no error, send the email
if(!isset($hasError))
{
echo "OK";
$emailTo = "sahil7771#gmail.com"; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nMobile No: $phone_no \n\n Your Industry: $vehicle \n\
\n\n Your Requirement: $require \n\n Your Solution: $solution \n\n
\n\n Message : $message
\n\nPlease Contact $name on $phone_no\n \n /====================================/ ";
$headers = 'From: Touch Active <'. $emailTo .'>' . "\r\n" . 'Reply-To: ' . $email;
if(mail($emailTo, 'Mail From Touch Active', $body, $headers))
{ //Replace Your Website Subject
$response=1;
$emailSent = true;
?>
<div id="responsive-container" ><p>Thanks For Messaging Us You Will Shortly Expect Our Assistance ( With In 24hrs ).</p></div>
<?php
}
else
{
?>
<div id="page-title"><h2>Failed To Sent</h2></div>
<?php echo "NOK";
echo $hasError;
echo $response;
$response=0;
}
}
else{
echo $hasError;
}
?>
Related
I've been trying to submit a form that is on my website but the form will not submit. I am not a php expert and I can not tell where my error is. The php file opens instead of sending to my two emails.
html
<form action="email.php" method="post" name="emailForm">
<div class="form-group">
<label for="Name"></label>
<input class="form-control name" placeholder="Name" id="Name" name="name">
</div>
<div class="form-group">
<label for="Email"></label>
<input class="form-control email" placeholder="Email" id="Email" name="email">
</div>
<div class="form-group">
<label for="Subject"></label>
<input class="form-control subject" placeholder="Subject" id="Subject" name="subject">
</div>
<div class="form-group">
<label for="Message"></label>
<textarea class="form-control Message" placeholder="Message" id="Message" name="message"></textarea>
</div>
<input type="submit" id="button" class="btn btn-default button_submit"></input>
</form>
and I have the php file in the main directory
and it contains
<?php
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$email_from = "georgestcm#gmail.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
$email_subject = "New Form submission";
$to = "georgestcm#gmail.com, yahwehown#gmail.com";
$email_body = "You have received a new message from the user $name.\n"."Here is the message:\n $message".
mail($to,$email_subject,$email_body,$headers);
?>
and my form validation is in in jquery. That is why I have not done it in php, because I am not a php expert.
jquery
$(document).ready(function() {
var name = $('input.name');
var email = $('input.email').prop('disabled',true);
var subject = $('input.subject').prop('disabled',true);
var message = $('textarea.Message').prop('disabled',true);
var button = $('input#button').prop('disabled',true);
name.on('keyup',function() {
if($(this).val().length > 0) {
email.prop('disabled',false);
} else {
email.prop('disabled',true);
}
});
email.on('keyup',function() {
if($(this).val().length > 0 && $(this).val().includes('#') && $(this).val().includes('.com')) {
subject.prop('disabled', false);
message.prop('disabled',false);
} else {
subject.prop('disabled', true);
message.prop('disabled',true);
button.prop('disabled',true);
}
});
message.on('keyup',function() {
if($(this).val().length > 0){
button.prop('disabled',false);
}
})
button.on('click', function() {
name.val('');
email.val('');
subject.val('');
message.val('');
})
})
I want to send email to my two emails.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Hello I have made a contact form on my website but when the user type in the details and submit the form, it sends some blank information and cannot find why. Also, a major issue, the form changes the name field for the countries one, so it came in like "Name: France" instead of "Name: John".
I have also added form validator from here https://github.com/1000hz/bootstrap-validator. Anyone know why this is happening?
Below are the js, the php and the html.
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Something went wrong! Did you fill in the form properly?");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var last = $("#last").val();
var email = $("#email").val();
var company = $("#company").val();
var users = $("#users").val();
var country = $("#country").val();
var msg_subject = $("#msg_subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "assets/php/form-process.php",
data: "name=" + name + "&last=" + last + "&email=" + email + "&company=" + company + "&users=" + users + "&country=" + country + "&msg_subject=" + msg_subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Message Submitted!")
}
function formError(){
$("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
$(this).removeClass();
});
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center tada animated text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// LAST NAME
if (empty($_POST["last"])) {
$errorMSG = "Last name is required ";
} else {
$name = $_POST["last"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// COMPANY
if (empty($_POST["company"])) {
$errorMSG = "Company name is required ";
} else {
$name = $_POST["company"];
}
// USERS
if (empty($_POST["users"])) {
$errorMSG = "Users number is required ";
} else {
$name = $_POST["users"];
}
// COUNTRY
if (empty($_POST["country"])) {
$errorMSG = "Country is required ";
} else {
$name = $_POST["country"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Subject is required ";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "info#email.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Last: ";
$Body .= $last;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Company: ";
$Body .= $company;
$Body .= "\n";
$Body .= "Users: ";
$Body .= $users;
$Body .= "\n";
$Body .= "Country: ";
$Body .= $country;
$Body .= "\n";
$Body .= "Subject: ";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);
// redirect to success page
if ($success && $errorMSG == ""){
echo "success";
}else{
if($errorMSG == ""){
echo "Something went wrong :(";
} else {
echo $errorMSG;
}
}
?>
<html>
<form id="contactForm" class="contact-form">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="sr-only">First name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="First Name" required data-error="Please enter your First name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="sr-only">Last name</label>
<input type="text" name="last" id="last" class="form-control" placeholder="Last Name" required data-error="Please enter your Last name">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<!-- end of /.row -->
<div class="col-md-12">
<div class="form-group">
<label class="sr-only">Email address</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Your Email" required data-error="Please enter your Email address">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="sr-only">Company</label>
<input type="text" name="company" id="company" class="form-control" placeholder="Company" required data-error="Please enter your Company name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Users" class="sr-only legacy-label">Users</label>
<select class="form-control" id="users" input name="users" required data-error="Please select the User Number">
<option value="">Users Number</option>
<option value="1 - 3">1 - 3</option>
<option value="4 - 7">4 - 7</option>
<option value="8 - 12">8 - 12</option>
<option value="More than 13">More than 13</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="Country" class="sr-only legacy-label">Country</label>
<select class="form-control" id="country" input name="country" required data-error="Please select your Country">
<option value="">Select your country</option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
<option value="American Samoa">American Samoa</option>
<option value="Andorra">Andorra</option>
<option value="And so on...">And so on...</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<!-- end of /.row -->
<div class="col-md-12">
<div class="form-group">
<label class="sr-only">Subject</label>
<input type="text" name="msg_subject" id="msg_subject" class="form-control" placeholder="Subject" required data-error="Please enter your Subject">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="sr-only">Your Message</label>
<textarea name="message" id="message" class="form-control" rows="5" placeholder="Your Message" required data-error="Please enter your Message"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<button type="submit" id="submit" class="btn btn-base-alt btn-cmd">Send Message</button>
</form>
</html>
Any help would be much appreciated :)
One of your problem is the variable attribution, each input should have is own variable
You make
$name = $_POST["name"];
...
$name = $_POST["last"];
...
$name = $_POST["company"];
...
$name = $_POST["users"];
...
$name = $_POST["country"];
You should have
$name = $_POST["name"];
...
$last = $_POST["last"];
...
$company = $_POST["company"];
...
$users = $_POST["users"];
...
$country = $_POST["country"];
The last attribution is the country, that why you have
Name: France" instead of "Name: John"
Wish you all a happy 2015!
I have a simple contact us php form. I am validating it with parsley.js. The validation works fine but I am receiving a lot of spam mails.
I believe if I can force the form to be submitted only if Jquery is enabled, then it should solve my problem (right?).
I'm not an expert with PhP/ Jquery and any help will be appreciated.
Here is my PHP code
<?php
// Define Variables i.e. name tag, as per form and set to empty
$contact_name = $contact_email = $contact_phone = $contact_message = "";
// Sanitize data and use friendly names
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["contact_name"]);
$email = test_input($_POST["contact_email"]);
$phone = test_input($_POST["contact_phone"]);
$message = test_input($_POST["contact_message"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Set values
$to = 'info#foryourservice.in';
$subject = 'New Message from Website';
$headers = 'From: info#domainname.com' . "\r\n" .
'Reply-To: info#domainname.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Set Email content
$emailcontent = "A new message has been submitted from the website.
\n
Name : $name
Email : $email
Phone : $phone
Message : $message";
// Mail function
$send_contact=mail($to,$subject,$emailcontent,$headers);
if($send_contact){
header('Location: index.php#contactusform');
}
else {
echo "<script type='text/javascript'>alert('We encountered an ERROR! Please go back and try again.');</script>";
}
?>
Here is my HTML ( Im using Twitter Bootstrap)
<form role="form" method="POST" action="contactusform.php" id="contactusform" data-parsley-validate>
<div class="col-xs-6">
<div class="form-group" style="margin-bottom: -5px">
<label for="input1"></label>
<input type="text" name="contact_name" class="form-control" id="input1" placeholder="Name*" required data-parsley-required-message="Please enter your name">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input2"></label>
<input type="email" name="contact_email" class="form-control" id="input2" placeholder="Email Address*" data-parsley-trigger="change" required data-parsley-required-message="Please enter a valid Email address">
</div>
<div class="form-group" style="margin-bottom: -5px">
<label for="input3"></label>
<input type="tel" name="contact_phone" class="form-control" id="input3" placeholder="Phone Number*" required data-parsley-type="digits" data-parsley-minlength="10" data-parsley-maxlength="10" data-parsley-required-message="Please enter a 10 digit number">
</div>
<br>
<div class="form-group">
<button type="submit" id="contactbutton" class="btn btn-primary" style="background-color: #A8B645; border-color: transparent">Submit</button>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="input4"></label>
<textarea name="contact_message" class="form-control" rows="7" id="input4" placeholder="Message*" required required data-parsley-required-message="Say something!"></textarea>
</div>
</div>
</form>
This is what the Spam Email looks like :
A new message has been submitted from the website.
Name : お買い得アナスイ ミロード大壳り出しランキング
Email : rsilau#gmail.com
Phone : お買い得アナスイ ミロード大壳り出しランキング
Message : Shoppers takes the boast on bag
お買い得アナスイ ミロード大壳り出しランキング http://www.frkapaun.org/dyqfmnwg/ysl-annasuixmraAekm.asp
Add a hidden field to your form:
<input type="hidden" value="0" id="botcheck" name="botcheck" />
Then with jQuery set the value to 1:
$("#botcheck").val("1");
Then server-side check the value of $_POST["botcheck"].
You might want to check if your form is submitted using ajax:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Process form here
}
For further explanation
I have a pet registration form where people can add a new pet.
People will click the add pet button and jquery clones the pet portion of the form and changes the id to #pet-2, another, #pet-3 and so on.
After fruitless web searching, I now need to know how to send this via php and ajax.
I have already created an ajax function for my contact forms as well as have php code to send the contact forms so would, ideally, want to modify that code in a separate file to handle the register pet also.
Here is the fiddle: http://jsfiddle.net/zsxe44c8/
Here is the code for the add pet form:
<form id="register-pet-form" data-quantity="1">
<fieldset id="practiceField" class="row">
<div class="col-md-6 push-md-6">
<h3>Practice</h3>
<select name="practice">
<option value="">Value 1</option>
<option value="">Value 2</option>
</select>
</div>
</fieldset>
<!--/#practiceField-->
<fieldset id="ownerDetails" class="row">
<div class="col-md-6">
<h3>Your details</h3>
<select name="title">
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Ms">Ms</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
</select>
<input name="fname" type="text" placeholder="First Name">
<input name="lname" type="text" placeholder="Last Name">
<input name="number" type="text" placeholder="Contact Number">
<input name="email" type="text" placeholder="Email Address">
</div>
<div class="col-md-6">
<h3>Your Address</h3>
<input name="address1" type="text" placeholder="Address 1">
<input name="address2" type="text" placeholder="Address 2">
<input name="address3" type="text" placeholder="Address 3">
<input name="postcode" type="text" placeholder="Postcode">
</div>
</fieldset>
<!--/#ownerDetails-->
<fieldset id="pet-1" class="row">
<div class="col-md-12">
<h3>Pet Details</h3>
</div>
<div class="col-md-6">
<input name="pet-name" type="text" placeholder="Pet Name">
<input name="pet-breed" type="text" placeholder="Pet Breed">
<input name="pet-age" type="text" placeholder="Age of pet">
</div>
<div class="col-md-6">
<select name="petGender">
<option value="Female">Female</option>
<option value="Male">Male</option>
</select>
<select name="petType">
<option value="Dog">Dog</option>
<option value="Cat">Cat</option>
<option value="Rabbit">Rabbit</option>
<option value="Gerbil">Gerbil</option>
<option value="Guinea Pig">Guinea Pig</option>
<option value="Hamster">Hamster</option>
<option value="Mouse">Mouse</option>
<option value="Rat">Rat</option>
<option value="Chinchilla">Chinchilla</option>
<option value="Other">Other</option>
</select>
</div>
<div class="col-md-12">
<input name="pet-desc" type="text" placeholder="Pet Description">
<textarea name="additional-comments" placeholder="Additional Comments"></textarea>
</div>
</fieldset>
<!--#petDetails-->
<div id="form-tools" class="row">
<div class="col-md-6">
<a class="add-pet" href="#">Add another pet</a>
</div>
<div class="col-md-6 right">
<input type="submit" value="Submit">
</div>
</div>
<!--/#form-tools-->
</form>
Here is the jQuery code for the add pet form:
function registerPet() {
function addPetRegistrationForm() {
var container = $('#register-pet-form'),
lastForm = $('#register-pet-form fieldset:last-of-type'),
currentForm = $('#pet-1'),
newForm = currentForm.clone(),
currentVal = parseInt(container.attr('data-quantity'), 10),
newVal = currentVal + 1;
$('h3', newForm).after('<a data-id="' + newVal + '" class="js-remove-pet remove-pet" href="#">Remove this pet</a>');
$('input, select', newForm).each(function () {
var newId = this.id.substring(0, this.id.length - 1) + newVal;
$(this).prev().attr('for', newId);
this.name = this.id = newId;
});
lastForm.after(newForm.attr('id', 'pet-' + newVal));
container.attr('data-quantity', newVal);
}
function removePetRegistrationForm(target) {
$('#pet-' + target).remove();
}
function handleRegisterPet() {
if($('#pet-1').length) {
$('#pet-1').addClass('ispet');
$('#pet-1 *[name]').each(function(){
$(this).attr('name',$(this).attr('name') + '[]');
});
var newBlock = $('#pet-1').html();
$('#pet-1').after('Add another pet');
$('.add-pet').on('click',function() {
var count = $('.ispet').length + 1;
$('.ispet').last().after('<fieldset id="pet-'+ count +'" class="ispet">' + newBlock + '</fieldset>');
return false;
});
}
}
$('.add-pet').on('click', function () {
addPetRegistrationForm();
return false;
});
$('#register-pet-form').on('click', '.js-remove-pet', function () {
removePetRegistrationForm($(this).attr('data-id'));
return false;
});
}
Now here is the code for the ajax contact form that is working and I wish to modify for the add pet form:
function ajaxForm(formID) {
var form = $(formID);
var formMessages = $('#form-messages');
$(formMessages).hide();
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function() {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(form).hide();
$('#fname').val('');
$('#lname').val('');
$('#email').val('');
$('#phone').val('');
$('#message').val('');
$(formMessages).html(
'<div class="alert alert-success" role="alert"><i class="fa fa-check"></i> <strong>Your message has been sent successfully</strong></div>'
).fadeIn();
})
.fail(function() {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
}
function practiceOneContact() {
ajaxForm('#practice-1-contact-form');
}
function practiceTwoContact() {
ajaxForm('#practice-2-contact-form');
}
function practiceThreeContact() {
ajaxForm('#practice-3-contact-form');
}
function practiceFourContact() {
ajaxForm('#practice-4-contact-form');
}
And finally, the PHP code for the contact form handler that I wish to modify to allow for dynamic pets from the add pet form:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$fname = strip_tags(trim($_POST["fname"]));
$fname = str_replace(array("\r","\n"),array(" "," "),$fname);
$lname = strip_tags(trim($_POST["lname"]));
$lname = str_replace(array("\r","\n"),array(" "," "),$lname);
$phone = strip_tags(trim($_POST["phone"]));
$phone = str_replace(array("\r","\n"),array(" "," "),$phone);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
$sendTo = strip_tags(trim($_POST["sendTo"]));
$practice = trim($_POST["practice"]);
echo 'field editing done';
// Check that data was sent to the mailer.
if ( empty($fname) OR empty($lname) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = $sendTo;
// Set the email subject.
$subject = "New contact from $fname $lname";
// Build the email content.
$email_content = "Practice Name: $practice\n";
$email_content .= "First Name: $fname\n";
$email_content .= "Last Name: $lname\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Phone: $phone\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $fname $lname <$email>";
echo 'section build done';
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
echo "There was a problem with your submission, please try again.";
}
The URLS for this project are as follows: http://cvs.dev.dannycheeseman.me/base/about-us/register-your-pets/
Register Pet: http://cvs.dev.dannycheeseman.me/base/contact-us/
Thank you for your time.
Seems like you want to post the whole form, including the input files generated dynamically.
if so, then you will want to see into using array of input.
<form method="POST" action="whereever.php>
<input type="text" name="name[]" value="Dog" />
<input type="text" name="name[]" value="Cat" />
<input type="text" name="name[]" value="Snake" />
</form>
When the form is sent (whether by basic or AJAX), the PHP script can read the input as an array
<?php
echo $_POST['name'][0]."<br>";
echo $_POST['name'][1]."<br>";
echo $_POST['name'][2]."<br>";
?>
above script will output
Dog
Cat
Snake
This can be applied to all input.
Does this help?
Addition
So in your case, you can do it like this:
<form>
<section>
Pet # 1
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>
<section>
Pet # 2
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>
<section>
Pet # 3
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>
</form>
To read the POST dynamically
foreach($_POST["name"] as $key => $value)
{
echo $value;
/*or if you want to loop while accessing other fields too, you can do this*/
echo "<br>".$_POST["name"][$key];
echo "<br>".$_POST["lastname"][$key];
/*this way you can access the other fields with the same <section> as well, just make sure you do not mess with the input placement*/
}
I have a form that I am trying to process payments for by following this example (https://gist.github.com/boucher/1750375). I am using PHP and Stripe.js and I keep getting this error:
The 'exp_month' parameter should be an integer (instead, is undefined)
Below is the code I am using. Am I missing something obvious?
<?php
session_start();
$name = htmlspecialchars($_POST['name']);
$description = "Test Transaction";
$amount = trim($_POST['amount']);
$email = htmlspecialchars(trim($_POST['email']));
$receipt_error = "Email receipt did not send!";
require_once 'includes/stripe-php-1.12.0/lib/Stripe.php';
if ($_POST) {
Stripe::setApiKey("sk_test_XXXXXX");
$error = '';
$success = '';
try {
if (!isset($_POST['stripeToken']))
throw new Exception("The Stripe Token was not generated correctly");
Stripe_Charge::create(array("amount" => $amount * 100,
"description" => $description,
"currency" => "usd",
"card" => $_POST['stripeToken']));
//PREPARE EMAIL
$to = $email;
$subject = "Receipt";
$headers =
'From: XXXX ' . "\r\n" .
'Reply-To: XXXX ' . "\r\n" .
'Bcc: XXXX' . "\r\n" .
'Content-type: text/html' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
include_once('includes/email_receipt.php'); //Sent $message
//Send the email!
if(mail($to,$subject,$message,$headers)){
header("Location: thank-you.php");
}
else{
die($receipt_error);
}
}
catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<!-- jQuery is used only for this example; it isn't required to use Stripe -->
<script type="text/javascript">
// this identifies your website in the createToken call below
Stripe.setPublishableKey('pk_test_XXX');
function stripeResponseHandler(status, response) {
if (response.error) {
// re-enable the submit button
$('.submit_button').removeAttr("disabled");
// show the errors on the form
$(".payment-errors").html(response.error.message);
} else {
var form$ = $("#donation_form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
$(document).ready(function() {
$("#donation_form").submit(function(event) {
// disable the submit button to prevent repeated clicks
$('.submit_button').attr("disabled", "disabled");
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: $('.number').val(),
name: $('.name').val(),
description: $('.description').val(),
cvc: $('.cvc').val(),
exp_month: $('.exp_month').val(),
exp_year: $('.exp_year').val()
}, stripeResponseHandler);
return false; // submit from callback
});
});
</script>
<form method="post" action="" class="reply-input" id="donation_form" >
<div class="input-block">
<label for="amount" class="label_comment"><strong>Donation Amount</strong>*</label>
<input type="text" name="amount" value="<?php echo $_POST['amount']; ?>" placeholder="$" data-stripe="amount" id="amount" required="">
</div>
<div class="input-block">
<label for="name" class="label_comment"><strong>Cardholder Name</strong>*</label>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" data-stripe="name" id="name" required="">
</div>
<div class="input-block">
<label for="email" class="label_comment"><strong>Email</strong>*</label>
<input type="email" name="email" value="<?php echo $_POST['email']; ?>" data-stripe="email" id="email" required="">
</div>
<div class="input-block">
<label for="credit_card" class="label_comment"><strong>Credit Card Number</strong>*</label>
<input type="number" name="credit-card" value="" id="credit_card" data-stripe="number" required="">
</div>
<div class="input-block">
<label for="cvc" class="label_comment"><strong>CVV</strong>*</label>
<input type="number" name="cvc" value="" data-stripe="cvc" id="cvv" required="" maxlength="4">
</div>
<div class="input-block">
<label for="exp_month" class="label_comment"><strong>Expiration Month</strong>*</label>
<div class="clear"></div>
<select name='exp_month' id='exp_month' data-stripe="exp-month">
<option value=''>Month</option>
<option value='01'>Janaury</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>
<option value='06'>June</option>
<option value='07'>July</option>
<option value='08'>August</option>
<option value='09'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select>
<select name='exp_year' id='exp_year' data-stripe="exp-year">
<option value="">Year</option>
<?php
for($i=0;$i<21;$i++){
echo "<option value='".(date('Y')+$i)."'>".(date('y')+$i)."</option>\n";
}
?>
</select>
</div>
<input type="submit" class="btn btn-success btn-large submit_button" value="Click to Donate Today">
<div class="clear"></div>
</form>
In your code, you're querying by classname '.exp_month' when there isn't a class with '.exp_month' in your HTML. If you're trying to query by id, it should be $('#exp_month')