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;
});
});
Related
I am trying to build a form for my website but It's not working. I have done all the debug but am unable to identify the issue as everything looks fine. Please find the code below:
JS Code:
// 13. contact form
if ($("#contactForm").length) {
setCsrf();
$("#contactForm").validator().on("submit", function(event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
submitMSG(false);
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
}
function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var comments = $("#comments").val();
var csrfToken = $("#csrfToken").val();
if (csrfToken) {
if (name && email && company && website && description && comments) {
$.ajax({
type: "POST",
url: "/libs/contact-form-process.php",
data: "name=" + name + "&email=" + email + "&comments=" + comments + "&csrfToken=" + csrfToken,
success: function success(text) {
if (text == "success") {
formSuccess();
} else {
submitMSG(false, text);
}
}
});
} else {
submitMSG(false, "Please enter the right information.");
}
} else {
submitMSG(false, "Invalid Token");
}
}
function formSuccess() {
$("#contactForm")[0].reset();
submitMSG(true);
}
function submitMSG(valid, msg) {
if (valid) {
$(".message-box").removeClass('d-none').addClass('d-block ');
$(".message-box div").removeClass('alert-danger').addClass('alert-success').text('Form submitted successfully');
} else {
$(".message-box").removeClass('d-none').addClass('d-block ');
$(".message-box div").removeClass('alert-success').addClass('alert-danger').text('Found error in the form. Please check again.');
}
}
function setCsrf() {
$.ajax({
url: 'libs/csrf.php',
type: "GET",
dataType: "json",
success: function success(data) {
if (data) {
document.getElementById("csrfToken").value = data.csrfToken;
}
},
error: function error(_error) {
console.log("Error " + _error);
}
});
PHP Code (contact-form-process.php)
<?php
session_start();
$errorMSG = "";
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["comments"];
// CSRF token check
if(empty($_SESSION["csrfToken"]) || ($_SESSION["csrfToken"] !== $_POST["csrfToken"])) {
$errorMSG .= "Invalid Token ";
}
// NAME
if (empty($name)) {
$errorMSG .= "Name is required ";
}
// EMAIL
if (empty($email)) {
$errorMSG .= "Email is required ";
}
// MESSAGE
if (empty($comments)) {
$errorMSG .= "Comments is required ";
}
// change email with your email
$emailTo = "info#****.com";
$subject = "*** Request";
// prepare email body text
$emailBody = " \n Name: ";
$emailBody .= $name;
$emailBody .= "\n";
$emailBody .= "Email: ";
$emailBody .= $email;
$emailBody .= "\n";
$emailBody .= "Additional Comments: ";
$emailBody .= $comments;
$emailBody .= "\n";
// send email
if(empty($errorMSG)) {
if (mail($emailTo, $subject, $emailBody, "From:".$email)){
echo "success";
}
}
else{
echo $errorMSG;
}
?>
HTML Code:
<form action="" method="POST" id="contactForm" class="contact-us-form">
<input type="hidden" name="csrfToken" id="csrfToken" value="" />
<div class="form-row">
<div class="col-md-9 col-12">
<h2>Become our Partner</h2>
<p>Fill out the application below and our team will contact you in 24 hours.</p>
</div>
<div class="col-md-9 col-12">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="Your Name *" required="required">
</div>
</div>
<div class="col-md-9 col-12">
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email *" required="required">
</div>
</div>
<div class="col-md-9 col-12">
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="5" cols="25" placeholder="Add some comments *"></textarea>
</div>
</div>
<div class="col-sm-12 mt-3">
<button type="submit" class="btn btn-brand-01" id="btnContactUs">
Apply Now
</button>
</div>
</div>
</form>
I keep getting the error "Found error in the form. Please check again."
Please help.
Project structure is as follows
C:\xampp\htdocs\myProject\Documentation
C:\xampp\htdocs\myProject\HTML\css
C:\xampp\htdocs\myProject\HTML\images
C:\xampp\htdocs\myProject\HTML\js
C:\xampp\htdocs\myProject\HTML\videos
C:\xampp\htdocs\myProject\HTML\404.html
C:\xampp\htdocs\myProject\HTML\contact.php
C:\xampp\htdocs\myProject\HTML\index.html
C:\xampp\htdocs\myProject\PSD
I have a contact form in index.html that is controlled by a javascript file. This code stops default form submit, performs error checks and then uses ajax to make a post request to contact.php. The javascript code runs, it detects the php (see the alert in the code below just after the axjax funtion call. The value of d is the php script in the alert, but none of the debug lines in the php code get called and it never returns 'success'.
Here is the form
<form class="form-horizontal" id="phpcontactform">
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Full Name" name="name" id="name">
</div>
<div class="control-group">
<input class="input-block-level" type="email" placeholder="Email ID" name="email" id="email">
</div>
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Mobile Number" name="mobile" id="mobile">
</div>
<div class="control-group">
<textarea class="input-block-level" rows="10" name="message" placeholder="Your Message" id="message"></textarea>
</div>
<div class="control-group">
<p>
<input class="btn btn-danger btn-large" type="submit" value="Send Message">
</p>
<span class="loading"></span> </div>
</form>
here is the javascript
// JavaScript Document
$(document).ready(function() {
$("#phpcontactform").submit(function(e) {
e.preventDefault();
var name = $("#name");
var email = $("#email");
var mobile = $("#mobile");
var msg = $("#message");
var flag = false;
if (name.val() == "") {
name.closest(".control-group").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".control-group").removeClass("error").addClass("success");
} if (email.val() == "") {
email.closest(".control-group").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".control-group").removeClass("error").addClass("success");
} if (msg.val() == "") {
msg.closest(".control-group").addClass("error");
msg.focus();
flag = false;
return false;
} else {
msg.closest(".control-group").removeClass("error").addClass("success");
flag = true;
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&mobile=" + mobile.val() + "&msg=" + msg.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "http://localhost/myProject/HTML/contact.php",
cache: false,
success: function (d) {
alert("d: "+d);
$(".control-group").removeClass("success");
if(d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="green">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="red">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").click(function () {
$(".control-group").removeClass("success").removeClass("error");
});
})
And finally here is the php
<?php
echo "<script>console.log('Debug Objects:' );</script>";
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$msg = $_REQUEST["msg"];
echo "<script>";
echo "alert('this also works');";
echo "</script>";
$to = "myemail#gmail.com";
if (isset($email) && isset($name) && isset($msg)) {
$subject = $name."sent you a message via Raaga";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: ".$name."<br/> Email: ".$email ."<br/> Mobile: ".$mobile." <br/>Message: ".$msg;
echo "<script>alert('this maybe works');</script>";
$mail = mail($to, $subject, $msg, $headers);
if($mail)
{
echo 'success';
}
else
{
echo "<script>alert('name:'+$name);</script>";
echo 'failed';
}
}
echo "<script>alert('this finally works');</script>";
?>
I tried moving contact.php to the htdocs root but that didnt work. Have turned off all antivirus and firewalls but that didnt work either. Am at a loss. Thought php was supposed to work out of the box with xampp?
Okay so thanks to ADyson for the help. The issue was not that php isn't running, its that the mail server was not properly configured.
I'm new to php and ajax.
I'm having an issue with a contact form I've created. It's not sending all of the information. I've isolated the issue and need an explanation as to why this is happening, I'll explain more below.
This is the HTML:
<section class="contact text-center " id="contact">
<div class="container">
<div class="row">
<!--Actual Form -->
<div class="col-md-8 col-xs-12 col-sm-12 col-sm-offset-2 col-sm-8">
<article class="contact-form">
<form role="form" id="contactForm" data-toggle="validator" class="shake">
<!-- FIRST ROW -->
<div class="row">
<div class="form-group col-sm-4">
<input type="text" class="form-control" id="name" placeholder="First Name * ">
</div>
<div class="form-group col-sm-4">
<input type="text" class="form-control" id="lname" placeholder="Last Name *">
</div>
<div class="form-group col-sm-4">
<input type="text" class="form-control" id="companyname" placeholder="Company name *">
</div>
</div>
<!-- SECOND ROW -->
<div class="row">
<div class="form-group col-sm-4">
<input type="text" class="form-control" id="jobtitle" placeholder="Job Title *">
</div>
<div class="form-group col-sm-4">
<input type="text" class="form-control" id="email" placeholder="Business Email *">
</div>
<div class="form-group col-sm-4">
<input type="tel" class="form-control" id="phonenumber" placeholder="Phone Number *">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<textarea id="message" class="form-control" rows="5" placeholder="Message *"></textarea>
</div>
<button onclick="myFunction()" class="btn btn-success btn-lg pull-right ">Submit</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
</article>
</div>
</div>
</div>
</section>
</div>
</div>
</section>
This is the php for the form.
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Name is required ";
} else {
$name = $_POST["name"];
}
// Last Name
if (empty($_POST["lname"])) {
$errorMSG = " Last Name is required ";
} else {
$lname = $_POST["lname"];
}
// Company Name
if (empty($_POST["companyname"])) {
$errorMSG = " Company Name is required ";
} else {
$companyname = $_POST["companyname"];
}
// Job Title
if (empty($_POST["jobtitle"])) {
$errorMSG = "Job Title is required ";
} else {
$jobtitle = $_POST["jobtitle"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Email is required ";
} else {
$email = $_POST["email"];
}
// Phone Number
if (empty($_POST["phonenumber"])) {
$errorMSG .= "Phone Number is required ";
} else {
$phonenumber = $_POST["phonenumber"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Message is required ";
} else {
$message = $_POST["message"];
}
$EmailTo = "farrun.wow#gmail.com";
$Subject = "New Message Received";
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Last Name: ";
$Body .= $lname;
$Body .= "\n";
$Body .= "Company Name: ";
$Body .= $companyname;
$Body .= "\n";
$Body .= "Job Title: ";
$Body .= $jobtitle;
$Body .= "\n";
$Body .= "Business Email Address: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Phone Number: ";
$Body .= $phonenumber;
$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;
}
}
?>
And this is the ajax:
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "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 lname = $("#lname").val();
var companyname = $("#companyname").val();
var jobtitle = $("#jobtitle").val();
var email = $("#email").val();
var email = $("#phonenumber").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
//data: "name=" + name + "&lname=" + lname + "&companyname=" + companyname + "&jobtitle=" + jobtitle + "&email=" + email + "&phonenumber=" + phonenumber + "&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);
}
The issue is here with this line
data: "name=" + name + "&email=" + email + "&message=" + message,
I can only have three entries in this, when I add any more to it the form breaks completely for some reason. The only three that send is "name", "email" and message"
Does anyone have any idea as to why?
First, a few observations.
Your form is submitting as the default GET method. Setting method="post" will line things up with your PHP script.
Your form inputs are missing a crucial element to process the form data without setting them manually as you are doing. E.G. name. Each element should have a name, to be referenced in either a post or get request.
Your method in the AJAX call for assigning the variables could (and should) be much simpler. See my example below.
The onClick event myFunction() does not exist in the code sample you provided.
Form HTML
Update the form method. Add name="field" to input and textarea.
<form id="contactForm" method="POST">
<input name="fname" id="fname" type="text" />
<input name="lname" id="lname" type="text" />
... other fields
<button id="contactSubmit" class="">Submit Form</button>
</form>
PHP
Can largely remain the same. Although, update the errorMsg to be as such.
// Init as empty
$errorMSG = '';
// NAME
if (empty($_POST["name"])) {
// Use .= to concat
$errorMSG .= "Name is required ";
} else {
$name = $_POST["name"];
}
// Last Name
if (empty($_POST["lname"])) {
// Use .= to concat
$errorMSG .= " Last Name is required ";
} else {
$lname = $_POST["lname"];
}
...etc
JavaScript
Structurally, you were pretty good. The AJAX is really all that changed.
function submitForm(){
var formData = $('#contactForm').serialize();
$.ajax({
type: "POST",
url: "path/to/form-process.php",
data: formData,
success: function(text) {
if (text == "success") {
// debug
console.log("success");
// ... other functions
} else {
// debug
console.log("error");
// ... other functions
}
}
});
}
I came across a problem with PHP form submission. I'm not able to read the captcha filed value in form submission. Here is the code
HTML
<div class="container">
<h2 class="centertitle">Contact Us</h2>
<div id="message"></div>
<form method="post" action="php/contact.php" name="contactform" id="contactform">
<div class="row">
<div class="col-sm-3">
<input type="text" name="name" placeholder="Name" id="name" class="form-control" />
</div>
<div class="col-sm-3">
<input type="text" name="email" placeholder="Email" id="email" class="form-control" />
</div>
<div class="col-sm-3">
<input type="text" name="phone" placeholder="Phone" id="phone" class="form-control" />
</div>
<div class="col-sm-3">
<div id="captcha">
<input type="text" name="verify" id="verify" class="form-control" placeholder="Enter Captcha" />
<img src="php/image.php" alt="well, this is out capcha image" class="captcha" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<input type="submit" name="send" value="Submit" id="submit" class="sbtn" />
</div>
</div>
</form>
</div><!-- /.container -->
Js Validation
$(document).ready(function() {
//Form Validation
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
//.after('<img src="images/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
subject: $('#subject').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});
});
Contact.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|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$verify = $_POST['verify'];
if(trim($name) == '') {
echo '<div class="error_message">Attention! You must enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Attention! Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Attention! Phone number can only contain digits.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Attention! You have entered an invalid e-mail address. Please try again.</div>';
exit();
}
if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please Verify CAPTCHA.</div>';
exit();
}else if(trim($verify) === $_SESSION["security_number"]) {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
$address = "contact#sreejesh.in";
$e_subject = 'Form Submission.';
$e_body = "You have a new Form Submission." . PHP_EOL . PHP_EOL;
$e_content = "Name: $name,\rPhone: $phone,\rEmail: $email" . PHP_EOL . PHP_EOL;
$e_reply = "";
$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 "<fieldset>";
echo "<div id='success_page'>";
echo "<h4>Email Sent Successfully.</h4>";
echo "<p>Thank you <strong>$name</strong>, for your interest We will contact you shortly.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
For some reason I'm NOT getting value of $captcha
It returns an error says**
Currently the form get submitted without validation.
For Captcha image I use this code -
Captcha Code(IMAGE.PHP)
<?php
session_start();
$img=imagecreatefromjpeg("texture.jpg");
$security_number = empty($_SESSION['security_number']) ? 'error' : $_SESSION['security_number'];
$image_text=$security_number;
$red=rand(100,255);
$green=rand(100,255);
$blue=rand(100,255);
$text_color=imagecolorallocate($img,255-$red,255-$green,255-$blue);
$text=imagettftext($img,16,rand(-10,10),rand(10,30),rand(25,35),$text_color,"fonts/courbd.ttf",$image_text);
header("Content-type:image/jpeg");
header("Content-Disposition:inline ; filename=secure.jpg");
imagejpeg($img);
?>
I'm a beginer in PHP & I'm sitting with this code for the last few hours. PLs help.
Here is a live URL - http://aisther.com/projects/sri/
Do not echo your session variable is it being created by your image.php script and exposing it to the user makes the captcha pointless.
HTML
<form action="contact.php" method="post">
<div id="captcha">
<img src="php/image.php" alt="well, this is out capcha image" class="captcha" />
<input type="text" name="verify" id="verify" class="form-control" placeholder="Enter Captcha" />
</div>
</form>
PHP
session_start();
if($_POST'verify'] == $_SESSION["security_number"]) {
echo 'captcha matched';
} else {
echo 'bad captcha';
}
If you want to use $_POST to read the form data, the form tag needs to look like
<form action='contact.php' method='post'>
Issue solved after adding session_start(); in contact.php
final code(contact.php)
<?php
session_start();
*********************************************************
$verify = $_POST['verify'];
$captcha = $_SESSION["security_number"];
*********************************************************
if(trim($verify) == '') {
echo '<div class="error_message">Attention! Please Verify CAPTCHA.</div>';
exit();
}else if(trim($verify) != trim($captcha)) {
echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>';
exit();
}
*********************************************************
?>
I am having a problem with my contact form where there is no success indication being given, even though the message is successfully sent to email. The form appears broken to the user because the page is unchanged when the submit button is pressed. This page was built using a Themeforest template, but the author is unable to provide a solution. I was hoping that someone could point me in the right direction.
Here is the stock 'contact-send.php' file I was given:
<?php
$names = $_POST['names'];
$email = $_POST['email_address'];
$comment = $_POST['comment'];
$to ='to#email.com';
$message = "";
$message .= "*Name: " . htmlspecialchars($names, ENT_QUOTES) . "<br>\n";
$message .= "*Email: " . htmlspecialchars($email, ENT_QUOTES) . "<br>\n";
$message .= "*Comments: " . htmlspecialchars($comment, ENT_QUOTES) . "<br>\n";
$lowmsg = strtolower($message);
$headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: \"" . $names . "\" <" . $email . ">\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$message = utf8_decode($message); mail($to, "Note from the Contact Form", $message, $headers);
if ($message){
echo 'sent';
}else{
echo 'failed';
}
?>
This is the stock html code:
<form id="contact-form" name="contact-form" action="" method="post">
<label class="contact-label">Name*</label>
<input class="contact-input" type="text" name="contact-names" value="" /><br /><span class="name-required"></span>
<label class="contact-label">Email*</label>
<input class="contact-input" type="text" name="contact-email" value="" /><br /><span class="email-required"></span>
<label class="contact-label">Message*</label>
<textarea name="comments" rows="2" cols="20" class="contact-commnent"></textarea><br /><span class="comment-required"></span>
<input type="submit" value="Send" id="submit-form" class="button lightred contact-submit" />
</form>
This file is attached to the html pages as well: (juery-contact.js)
$(document).ready(function(){
$('#submit-form').click(function(){
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var names = $('#contact-form [name="contact-names"]').val();
var email_address = $('#contact-form [name="contact-email"]').val();
var comment = $.trim($('#contact-form .contact-commnent').val());
var data_html ='' ;
if(names == ""){
$('.name-required').html('Your name is required.');
}else{
$('.name-required').html('');
}
if(email_address == ""){
$('.email-required').html('Your email is required.');
}else if(reg.test(email_address) == false){
$('.email-required').html('Invalid Email Address.');
}else{
$('.email-required').html('');
}
if(comment == ""){
$('.comment-required').html('Comment is required.');
}else{
$('.comment-required').html('');
}
if(comment != "" && names != "" && reg.test(email_address) != false){
data_html = "names="+ names + "&comment=" + comment + "&email_address="+ email_address;
//alert(data_html);
$.ajax({
type: 'post',
url: 'contact-send.php',
data: data_html,
success: function(msg){
if (msg == 'sent'){
$('#success').html('Message sent!') ;
$('#contact-form [name="contact-names"]').val('');
$('#contact-form [name="contact-email"]').val('');
$('#contact-form .contact-commnent').val('');
}else{
$('#success').html('Mail Error. Please Try Again.!') ;
}
}
});
}
return false;
})
})
Here is the live site if you need it: http://shamrockmasonry.ca/contact.html
Any help would be appreciated!
I glanced at the source code and noticed that there isn't an element with '#success' id.
So this block of code that adds html message to #success element can't do that because that element does not actually exist:
if (msg == 'sent'){
$('#success').html('Message sent!');
$('#contact-form [name="contact-names"]').val('');
$('#contact-form [name="contact-email"]').val('');
$('#contact-form .contact-commnent').val('');
}else{
$('#success').html('Mail Error. Please Try Again.!') ;
}
To answer your additional question you made in the comments about removing the error messages you got after successful submit do the following.
Add additional class to your span's, like in example here
<span class="email-required error-message"></span>
<span class="name-required error-message"></span>
<span class="comment-required error-message"></span>
And add this line of code to your jquery block:
if (msg == 'sent'){
$('#success').html('Message sent!');
$('#contact-form [name="contact-names"]').val('');
$('#contact-form [name="contact-email"]').val('');
$('#contact-form .contact-commnent').val('');
$('.error-message').empty(); // clears all of the current error messages on success
}else{
$('#success').html('Mail Error. Please Try Again.!') ;
}
So add a div element with #success id above your form tag and you should be good.
Hope it helps.
Add <div id="success"></div> before form HTML
Should be:
<div id="success"></div>
<form id="contact-form" name="contact-form" action="" method="post">
[...]
</form>