I'm getting the following error for a contact form
Notice: Undefined variable: sumNums in C:\xampp\htdocs\tedx\contact.php on line 45
I've already tried 'isseting' it.
Below is my HTML markup regarding this.
<form class="contact-form" method="post" action="contact.php" name="contactform" id="contactform">
<div class="row">
<div class="large-6 columns">
<div class="row">
<div class="large-12 columns">
<label>Name<small class="astrix">*</small>
<input type="text" id="name" name="name" />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Email<small class="astrix">*</small>
<input type="text" id="email" name="email" />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Subject<small class="astrix">*</small>
<input type="text" id="subject" name="subject" />
</label>
</div>
</div>
</div>
<div class="large-6 columns">
<label>Message<small class="astrix">*</small>
<textarea cols="30" rows="8" id="comments" name="comments"></textarea>
</label>
</div>
</div>
<div class="row captcha">
<div class="large-6 columns">
<label for="captcha-code">Enter the following sum<small class="astrix">*</small><br>
<span class="captcha-chars" name="captcha-chars">
<span name="num1" id="num1">
<?php
$num1 = rand(1, 9);
echo $num1;
?>
</span>
+
<span name="num2" id="num2">
<?php
$num2 = rand(1, 9);
echo $num2;
?>
</span>
<?php $sumNums = $num1+$num2; ?>
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
</span>
<input type="text" id="verify" name="verify">
</label>
</div>
<div class="large-6 columns mt-25">
<button type="submit" id="submit" class="submit"><img src="img/btn-submit.png" alt=""></button>
</div>
</div>
</form>
And the PHP:
<?php
if(!$_POST) exit;
// 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|me|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 = trim($_POST['name']);
$email = trim($_POST['email']);
$subject = trim($_POST['subject']);
$comments = trim(strip_tags($_POST['comments'], '<p><b><a><i>'));
$verify = trim($_POST['verify']);
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
if(trim($name) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter your name.</div>';
exit();
} else if(!ctype_alpha($name)) {
echo '<div class="error_message"><i class="fi-x"></i>Your name should\'t contain digits or speicla characters</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter your email ID</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message"><i class="fi-x"></i>You have entered an invalid email ID, try again.</div>';
exit();
}
if(trim($subject) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter a subject.</div>';
exit();
} else if(!ctype_alpha($subject)) {
echo '<div class="error_message"><i class="fi-x"></i>Your subject should\'t contain digits or speicla characters</div>';
exit();
} else if(trim($comments) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter a message.</div>';
exit();
} else if(!isset($verify) || trim($verify) == '') {
echo '<div class="error_message"><i class="fi-x"></i>You must enter the verification number.</div>';
exit();
} else if(trim($verify) != $sumNums) {
echo '<div class="error_message"><i class="fi-x"></i>The verification number you entered is incorrect.</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 = "example#themeforest.net";
$address = "njshah#aixsol.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 with regards to $subject, 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.";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . 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 "<div id='success_page' class='success_message'>";
echo "<p><i class='fi-check'></i>Message sent successfully.";
echo "Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
} else {
echo 'ERROR!';
}
How do I solve this issue?
You need to answer yourself a question about the line below. Will the $sumNums be defined if the POST isn't submitted?
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
In form you gave wrong name for sunNums it should be sumNums
So, Replace
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
with
<input type="hidden" value="<?php echo $sumNums; ?>" name="sumNums" id="sumNums">
I have just changed the name attribute.
Your input has
name="sunNums"
and you are using
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
in HTML name is sunNums
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
but in PHP you use sumNums
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
Problem is this:
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
$sumNums variable is not defined. There is no such index in $_POST.
You can initialize the value
$sumNums = '';
before
if(isset($_POST['sumNums'])) {$sumNums = $_POST['sumNums'];}
Otherwise, you can also replace
} else if(trim($verify) != $sumNums) {
by
} else if(isset($sumNums) && trim($verify) != $sumNums) {
I hope it will help you :)
REPLACE:
<input type="hidden" value="<?php echo $sumNums; ?>" name="sunNums" id="sumNums">
TO
<input type="hidden" value="<?php echo $sumNums; ?>" name="sumNums" id="sumNums">
I am updating a client site and the simple contact form that used to work is now broken. It appears that the HTML form sends and receives data from the jQuery file as I get the error messages returned, though it is not passing the data through to the PHP file for sending an email. If I send the data direct from the HTML form to the PHP file, then an email is sent. The error is probably at the end of the jQuery, though my search for how to fix has not revealed an answer. Any ideas on how to make this work?
HTML Form
<form id="rsForm" action="#" onsubmit="return goContact(this);" name="rsForm">
<input id="formNam" type="hidden" name="formNam" value="3" />
<div class="CU_row">
<div class="CU_form_title"><label for="firstName">First Name:</label></div>
<div class="CU_form_entry"><input id="firstName" maxlength="120" size="39" name="first" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="lastName">Last Name:</label></div>
<div class="CU_form_entry"><input id="lastName" maxlength="120" size="39" name="last" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="emailAddress">Email:</label></div>
<div class="CU_form_entry"><input id="emailAddress" maxlength="120" size="39" name="email" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="subjectLine">Subject:</label></div>
<div class="CU_form_entry"><input id="subjectLine" maxlength="120" size="39" name="subject" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="messageCopy">Message:</label></div>
<div class="CU_form_entry"><textarea id="messageCopy" rows="6" cols="30" name="message"></textarea> <span class="redT">*</span></div>
</div>
<div id="CU_reset"><input type="reset" value="Reset" /></div>
<div id="CU_submit"><input type="submit" name="Submit" value="Submit" /></div>
jQuery File
// JavaScript Document
function goContact(theForm){
//Validate the forms and create the array to send.
var frmName = theForm.formNam.value;
//Validate Common elements.
if(theForm.firstName.value.length < 1){
alert("You must supply a First Name");
theForm.firstName.focus();
return false;
}
if(theForm.lastName.value.length < 1){
alert("You must supply a Last Name");
theForm.lastName.focus();
return false;
}
if(theForm.email.value.length < 1){
alert("You must supply an Email");
theForm.email.focus();
return false;
}
if(theForm.subjectLine.value.length < 1){
alert("You must supply a Subject");
theForm.subjectLine.focus();
return false;
}
if(theForm.messageCopy.value.length < 1){
alert("You must supply a Message");
theForm.messageCopy.focus();
return false;
}
sendAjaxReq($(theForm).serialize(true));
return false;
}
function showResult(messageText){
//Show the pop up with the confirmation.
$('msgWindow').innerHTML = messageText;
$('rsForm').reset();
$('frmInter').hide();
}
function sendAjaxReq(formEms){
//Send he ajax request
var rSp = new Ajax.Request("includes/sendContact.php", {
method: 'get',
parameters: formEms,
onComplete: receiveRespon});
}
function receiveRespon(oReq, JSONRsp){
//Receive the response from the ajax request.\
var result = JSONRsp;
if(result){
showResult(result);
}
}
PHP File
<?php
if(isset($_GET['Submit'])){
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: no-reply#sitename.com' . "\r\n";
'X-Mailer: PHP/' . phpversion();
$to = "info#sitename.com";
$subject = "Inquiry from " . $_SERVER['HTTP_HOST'];
$message = "A client has sent a contact us email\n\n";
foreach($_GET AS $field => $value) {
$message .= "field = $field, value = $value \n\n";
}
$mailSent = mail($to, $subject, $message, $headers);
$arr = "Your message has been received.";
header('X-JSON: ('.json_encode($arr).')');
}
?>
i have a one page portfolio with a contact form, i have been trying to troubleshoot this thing but have not succeeded. I am no PHP expert so I will try to explain as best as I can. Basically what I have is a contact template file from word press that i have used in the past, but what i want to do is (if possible) implement in my portfolio. My main issue is that when I preview my site in the browser it shows the PHP code that is on the form.
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// Check fields for errors
if (empty($_POST["txtName"])) {
$errors["txtName"] = "Please enter your name.";
}
if (empty($_POST["txtPhone"])) {
$errors["txtPhone"] = "Please enter your phone number.";
}
if (empty($_POST["txtEmail"])) {
$errors["txtEmail"] = "Please enter your email address.";
} else {
if (!eregi('^[[:alnum:]][a-z0-9_\.\-]*#[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST["txtEmail"])))) {
$errors["txtEmail"] = "Please provide a valid email address.";
}
}
if (count($errors) < 1) {
$to = "test-email#gmail.com";
$subject = 'Bave Designs Contact';
$headers = "From:" . $_POST["txtEmail"] . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$message = '<html><body style="font-family:Arial, Helvetica, sans-serif; font-size:12px;">';
$message .= '<p><strong>Name:</strong> ' . $_POST["txtName"] . '<br />
<strong>Phone:</strong> ' . $_POST["txtPhone"] . '<br />
<strong>Email:</strong> ' . $_POST["txtEmail"] . '<br />
<strong>Message:</strong><br />' . $_POST["txtComment"] . '</p>
</body>
</html>';
if ( !mail($to,$subject,$message,$headers) ) {
$errors["send"] = "There was a problem sending your message. Please try again.";
}
}
}
<div id="contact-form">
<?php
if (count($errors) > 0) {
echo '<ul style="color:red; padding:0 0 18px 22px;">';
foreach ($errors as $error) {
echo "<li>" . $error . "</li>";
}
echo "</ul>";
}
?>
<?php if ($_SERVER['REQUEST_METHOD'] == "POST" && count($errors) < 1) { ?>
<p class="success-message"><?php _e('Thank you! Your message has been sent.'); ?></p>
<?php } else { ?>
<form id="contact1" method="post" action="#message" class="contact-form">
<p><label for="txtName">Name</label>
<input type="text" id="txtName" name="txtName" class="field" size="40" value="<?php echo $_POST['txtName'] ?>" /></p>
<p><label for="txtPhone">Phone</label>
<input type="text" id="txtPhone" name="txtPhone" class="field" size="40" value="<?php echo $_POST['txtPhone'] ?>" /></p>
<p><label for="txtEmail">Email</label>
<input type="text" id="txtEmail" name="txtEmail" class="field" size="40" value="<?php echo $_POST['txtEmail'] ?>" /></p>
<p><label for="txtComment">Message</label>
<textarea name="txtComment" id="txtComment" class="field" cols="40" rows="10"><?php echo $_POST['txtComment'] ?></textarea></p>
<p><input type="submit" id="btnSubmit" name="btnSubmit" class="button" value="Submit" /></p>
</form>
<?php } ?>
</div><!-- CONTACT FORM ENDS-->
I switched the wp_mail function to mail which I know is correct.
Any help would be appreciated.
Thanks in advance.
My main issue is that when I preview my site in the browser it shows
the PHP code that is on the form.
So, if I understand correctly, your PHP codes are being shown in your page?
If that is the case, I urge you to contact your webhosting provider asap, because there seems to be a big problem with your Apache configuration.
Before I begin please except my appologises if this is to long, I'm totaly new to Html5 (usually design in Flash)and just getting started. I recently downloaded a free template called Brownie and understand most things but the contact form. It's using Javascript, PHP and Ajax I think. Ive got it kinda workin locally but things aren't working how I want. What I'm trying to do is make it validate fields with error message or success message e.t.c. this is the html form code I have:
<p class="required_info"><span>*</span> Required</p>
<!-- SUCCESS MESSAGE -->
<div class="success_box none"> Email successfully sent. Thank you! </div>
<!-- END SUCCESS MESSAGE -->
<!-- START CONTACT FORM -->
<form action="#" class="contact_form">
<p>
<label for="name">Name <span>*</span></label>
<input type="text" class="inputText" id="name" name="name" placeholder="Please enter your full name" pattern="[a-zA-Z ]+" onkeypress="return alpha(event,letters)" required minlength="5" maxlength="50" onpaste="return false;" tabindex="1"/>
<div class="success_title none"> You've entered your name. </div>
<div class="error_title none">* Please enter your full name. </div>
</p>
<div class="clear"></div>
<p>
<label for="company">Company </label>
<input type="text" class="inputText" id="company" name="company" placeholder="Company Name" minlength="3" maxlength="50" onpaste="return false;" tabindex="2"/>
</p>
<div class="clear"></div>
<p>
<label for="email">E-mail <span>*</span></label>
<input type="text" class="inputText" id="email" name="email" placeholder="Please enter a valid email address" required minlength="5" maxlength="50" onpaste="return false;" tabindex="3"/>
<div class="error_title none">* Please enter a valid email. </div>
</p>
<div class="clear"></div>
<p>
<label for="message">Message <span>*</span></label>
<textarea class="inputTextarea" cols="88" rows="6" id="message" name="message" placeholder="Please enter your message" required tabindex="4"></textarea>
<div class="error_title none">* Please enter your message. </div>
</p>
<div class="clear padding20"></div>
<p class="submit"><input type="reset" class="resetBtn button white" onclick="resetFields()" value="Reset" /> Send </p>
</form>
<!-- END CONTACT FORM -->
<!-- ERROR MESSAGE -->
<div class="error_box none"> Please complete all required fields [ highlighted in red ]. </div>
<!-- END ERROR MESSAGE -->
and this is the javascript code:
$(document).ready(function () {
$('#name').focus(function () {
$(this).removeClass('error_class');
});
$('#email').focus(function () {
$(this).removeClass('error_class');
});
$('#message').focus(function () {
$(this).removeClass('error_class');
});
$('.contact_form').submit(function () {
hasError = false;
if ($('#name').val() == '') {
$('#name').addClass('error_class');
hasError = true;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $('#email').val();
if (emailaddressVal == '') {
$('#email').addClass('error_class');
hasError = true;
}
else if (!emailReg.test(emailaddressVal)) {
$('#email').addClass('error_class');
hasError = true;
}
if ($('#email').val() == '') {
$('#email').addClass('error_class');
hasError = true;
}
if ($('#message').val() == '') {
$('#message').addClass('error_class');
hasError = true;
}
if (hasError == true) {
$('.info_box').hide();
$('.error_box').show();
$('.error_title').show();
}
else {
$.ajax({
type: 'POST',
url: 'contact.php',
cache: false,
data: $(".contact_form").serialize(),
success: function (data) {
if (data == "error") {
$('.success_box').hide();
$('.success_title').hide();
$('.error_box').show();
$('.error_title').show();
}
else {
$('.error_box').hide();
$('.error_title').hide();
$('.success_box').show();
$('.success_title').hide();
$('.resetBtn').hide();
$('.submit').hide();
}
}
});
}
return false;
});
});
This is the PHP code:
<?php
$your_email = 'name#domain.com'; // Your email address
$subject = 'Email from your contact form'; // Email subject
$name = isset($_POST['name']) && $_POST['name'] ? $_POST['name'] : ''; // Visitor Name
$company = isset($_POST['company']) && $_POST['company'] ? $_POST['company'] : ''; // Visitor Company
$email = isset($_POST['email']) && $_POST['email'] ? $_POST['email'] : ''; // Visitor Email
$message = isset($_POST['message']) && $_POST['message'] ? $_POST['message'] : ''; // Visitor Message
$website = isset($_POST['website']) && $_POST['website'] ? $_POST['website'] : ''; // Visitor Message
$full_message = 'Website: '.$website. "\r\n\r\n Message:".$message;
if($name && $email && $message)
{
$headers = 'From: '.$name.' <'.$email.'>' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= 'Content-type: text/plain; charset=UTF-8' . "\r\n";
//------------------------------------------------
// Send out email to site admin
//------------------------------------------------
if(#mail($your_email, $subject, $full_message, $headers))
die("success");
else
die("error");
}
else
{
die("error");
}
?>
When the send button is pressed i want it to check if any data has been entered in each input field - if yes add success message if no add error message. I have the error message working but cant get the success message working on individual input fields. Any sugestions would be helpful...
I suspect it is because you are assigning true or false to each variable instead of the value of the variable in your php script. Isset($_POST[test]) is true, not the value of the test form value.
I've got a php / ajax form that works 100% ... but I need a few of the same form on the SAME page. Of course each of the forms will go to a different recipient.
I tried duplicating the form and it seems very complicated! I've tried submitting the duplicated form (with lots of edits to the duplicated form to try get it working) but no success
I don't know if what I am doing is right.
How the form goes is, I have a button when clicked, it toggleslides the div which contains the form... fill in the form, hit submit and an ajax success message pops up saying thank you
HTML FORM:
<body>
<div id="container">
<div id="accommodation_listing_options_box">
<ul id="accommodation_listing_options">
<li>Price Range: <a href="#" class="tooltip" style="cursor:help;" title="Mid-range
Accommodation"><img src="../mid-range-yellow.png" width="28" height="19"
align="absmiddle" style="padding-left:0px;" /></a></li>
<li><a href="#">View
Comments</a> <img src="../comments_bubble_small.png" width="18" height="16"
align="absmiddle" style="padding-left:5px;" /></li>
</ul>
</div>
<div id="quick_enquiry_box">Make Quick Enquiry</div>
<div style="clear:both; width:710px;"></div>
<div style="clear:both;"></div>
<div id="slide_panel">
<div id="contact">
<div id="message"></div>
<form method="post" action="contact.php" name="contactform"
id="contactform">
<div id="my_contact_left">
<label for="name" accesskey="U"><span class="required">*
</span>Name</label><br />
<input name="name" type="text" id="name" size="30" />
<br />
<label for="email" accesskey="E"><span class="required">*
</span>Email</label><br />
<input name="email" type="text" id="email" size="30" />
<br />
<label for="phone" accesskey="P"><span class="required">*
</span>Phone:</label><br />
<input name="phone" type="text" id="phone" size="30" />
<br />
<label for="dayin" accesskey="P">Day in:</label><br />
<input name="dayin" class="datepicker" type="text" id="dayin"
size="30" />
<br />
<label for="dayout" accesskey="P">Day out:</label><br />
<input name="dayout" class="datepicker2" type="text" id="dayout"
size="30" />
</div>
<div id="my_contact_right">
<label for="comments" accesskey="C"><span class="required">*
</span>Your Comments</label><br />
<textarea name="comments" cols="40" rows="3" id="comments"
style="width: 350px; height:100px;"></textarea>
<p><span class="required">*</span>Type the validation code in
below</p>
<div style="width:100px; height:40px; float:left;"><label
for="verify" accesskey="V"> <img src="image.php" alt="Image
verification" border="0"/></label></div>
<div style="width:310px; height:40px; float:right;"><input
name="verify" type="text" id="verify" size="6" value="" style="width: 50px;" />
<input type="submit" style="margin-left:112px;" class="submit"
id="submit" value="Send it!" /></div>
<div style="clear:both; width:410px;"></div>
</div>
<div style="clear:both; width:710px;"></div>
</form>
</div>
<div id="quick_form_wrapper_close"><a href="#"><img src="../close-panel-button.gif"
/></a></div>
</div>
</div>
</body>
If I make a duplicated form, what I need to change in the HTML code is the following:
action="contact.php" name="contactform"
id="contactform"
to:
action="contact2.php" name="contactform2"
id="contactform2"
Is this correct? Anything else I need to change in the HTML?
Moving onto the Javascript:
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$('#submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message").slideUp(750,function() {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
dayin: $('#dayin').val(),
dayout: $('#dayout').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message").show().delay(5000).fadeOut();
}
);
});
Do I need to make the field ID's different duplicating a form on the same page?
EG:
$.post(action, {
name2: $('#name2').val(),
email2: $('#email2').val(),
phone2: $('#phone2').val(),
dayin2: $('#dayin2').val(),
dayout2: $('#dayout2').val(),
comments2: $('#comments2').val(),
verify2: $('#verify2').val()
},
Do I need to do any changes to the PHP process form?
Here is the main part of the php process form:
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$dayin = $_POST['dayin'];
$dayout = $_POST['dayout'];
$comments = $_POST['comments'];
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
// Important Variables
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits.</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.
</li>';
}
if($error != '') {
echo '<div class="error_message">Attention! Please correct the
errors below and try again.';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
// Advanced Configuration Option.
// i.e. The standard subject will appear as, "You've been contacted by
John Doe."
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Advanced 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.
$msg = "You have been contacted by $name with regards to Accommodation.
They passed verification and their message is as follows." . PHP_EOL . PHP_EOL;
$msg .= "$comments" . PHP_EOL . PHP_EOL;
$msg .= "You can contact $name via email, $email or via phone $phone." .
PHP_EOL . PHP_EOL;
$msg .= "We want to stay from the $dayin to the $dayout" . PHP_EOL .
PHP_EOL;
$msg .=
"---------------------------------------------------------------------------
-" . PHP_EOL;
if($twitter_active == 1) {
$twitter_msg = $name . " - " . $comments . ". You can contact " .
$name . " via email, " . $email ." or via phone " . $phone . ".";
twittermessage($twitter_user, $twitter_msg, $consumer_key,
$consumer_secret, $token, $secret);
}
$msg = wordwrap( $msg, 70 );
$headers = "From: $email" . 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)) {
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<strong>Email Sent Successfully.</strong>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!'; // Dont Edit.
}
}
Thanks in advance! Really appreciate your help because I have tried for hours and I haven't got it right yet!
EDIT:
MY CURRENT JAVASCRIPT CODING:
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$('.submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message").slideUp(750,function() {
$('#message').hide();
$.post(action, {
name: $('.name').val(),
email: $('.email').val(),
phone: $('.phone').val(),
dayin: $('.dayin').val(),
dayout: $('.dayout').val(),
comments: $('.comments').val(),
verify: $('.verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('.contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('.submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
jQuery(document).ready(function(){
$('.contactform2').submit(function(){
var action = $(this).attr('action');
$('.submit').attr('disabled','disabled').after('<img src="assets/ajax-
loader.gif" class="loader" />');
$("#message2").slideUp(750,function() {
$('#message2').hide();
$.post(action, {
name: $('.name').val(),
email: $('.email').val(),
phone: $('.phone').val(),
dayin: $('.dayin').val(),
dayout: $('.dayout').val(),
comments: $('.comments').val(),
verify: $('.verify').val()
},
function(data){
document.getElementById('message2').innerHTML = data;
$('#message2').slideDown('slow');
$('.contactform2 img.loader').fadeOut('fast',function()
{$(this).remove()});
$('.submit').removeAttr('disabled');
if(data.match('success') != null);
$("#message2").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
MY CURRENT JAVASCRIPT CODE:
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$(this).children('.submit').attr('disabled','disabled').after('<img
src="assets/ajax-loader.gif" class="loader" />');
$(this).children("#message").slideUp(750,function() {
$(this).children('#message').hide();
$.post(action, {
name: $(this).children('.name').val(),
email: $(this).children('.email').val(),
phone: $(this).children('.phone').val(),
dayin: $(this).children('.dayin').val(),
dayout: $(this).children('.dayout').val(),
comments: $(this).children('.comments').val(),
verify: $(this).children('.verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$(this).children('#message').slideDown('slow');
$(this).children('.contactform
img.loader').fadeOut('fast',function(){$(this).remove()});
$(this).children('.submit').removeAttr('disabled');
if(data.match('success') != null);
$(this).children("#message").show().delay(5000).fadeOut();
}
);
});
return false;
});
});
Instead of using IDs for the jquery selectors, use classes. You can give all of the forms the same class name and the fields that are the same get the same classes as well.
Then, use those in your jquery:
$('.contactform').submit(function(){
$.post(action, {
name: $(this).children('.name').val(),
It should work for however many instances of the form you have because all of the input fields are referenced by $(this), which is the submitted form, regardless of id or name.
EDIT:
This should work for you. For any number of forms, this is all you would need.
jQuery(document).ready(function(){
$('.contactform').submit(function(){
var action = $(this).attr('action');
$('.submit', this).attr('disabled','disabled').after('<img src="assets/ajax-loader.gif" class="loader" />');
$('.message', this).slideUp(750,function() {
$('.message', this).hide();
$.post(action, {
name: $('.name', this).val(),
email: $('.email', this).val(),
phone: $('.phone', this).val(),
dayin: $('.dayin', this).val(),
dayout: $('.dayout', this).val(),
comments: $('.comments', this).val(),
verify: $('.verify', this).val()
},
function(data){
$('.message', this).html(data);
$('.message', this).slideDown('slow');
$('img.loader', this).fadeOut('fast',function() {
$(this).remove();
});
$('.submit', this).removeAttr('disabled');
if(data.match('success') != null);
$('.message', this).show().delay(5000).fadeOut();
});
});
return false;
});
});