I found a tutorial for a simple contact form using fancyBox. I was able to apply the form into my website, and then modify the code of the form to meet my needs. But my form is not working.
Once I put in all of the information into the form and I press the Send Email button, the button then disappears and I get a "sending..." which is what it supposed to do if all of the fields are "true". But it does not want to do the last step which is to run the php file.
The form also came with the php file necessary for this to work, but it doesn't send it.
Does the php file have to be in an specific place in the website? I have tried to place it from several different locations but to no avail.
<div id="inline">
<form id="contact" name="contact" action="#" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
<script type="text/javascript">
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var nameval = $("#name").val();
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
var namelen = nameval.length;
if(namelen < 2) {
$("#name").addClass("error");
}
else if(namelen >= 2) {
$("#name").removeClass("error");
}
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4 && namelen >= 2) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! We will respond to your request as soon as possible.</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
sendmessage.php
<?php
$sendto = "antiques47#aol.com";
$username = $_POST['name'];
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "More information request";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$username."</p>\r\n";
$msg .= "<p><strong>Email:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
I tried changing the ACTION on the form to the specific file, but it didn't work either.
I noticed that the ajax part also has the URL to send message.php, I tried to change that so it has a specific directory to the file but that did not work.
Updated:
You are changing the From: attribute in your mail headers. Some ISPs will block outgoing emails that do that. This could be your problem. Comment out the line:
$headers = "From: " . strip_tags($usermail) . "\r\n";
and try again.
If that fails, check each step of the AJAX:
.1. In sendmessage.php, change the very top of the file to read:
<?php
die('Got to here');
.2. Then, back in your ajax code block, amend it (temporarily) to read:
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
alert(data);
}
});
This will at least tell you if it is communicating.
.3. Then, echo back the POST items that you received, to ensure there isn't a problem there:
PHP:
$username = $_POST['name'];
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$out = 'username [' .$username. ']';
$out .= 'usermail [' .$usermail. ']';
$out .= 'content [' .$content. ']';
echo $out;
Again, see what is echo'd out by the ajax success function.
Related
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 have this problem with my contact form. When I submit the form I receive 2 identical emails in my box.
Im using JS to check the form for errors and then simple PHP mail() function to send the email.
Here is the PHP code:
<?php
$from = Trim(stripslashes($_POST['email']));
$to = "myemail#gmail.com";
$subject = "Contact Form";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$number = Trim(stripslashes($_POST['number']));
$message = Trim(stripslashes($_POST['message']));
$body = "";
$body .= "Name: ";
$body .= $name;
$body .= "\n\n";
$body .= "E-mail: ";
$body .= $email;
$body .= "\n\n";
$body .= "Telephone Number: ";
$body .= $number;
$body .= "\n\n";
$body .= "Message: ";
$body .= $message;
$body .= "\n\n";
$success = mail($to, $subject, $body, "From: <$from>" . "\r\n" . "Reply-to: <$from>" . "\r\n" . "Content-type: text; charset=utf-8");
?>
And here is the JS:
$(".submit").click(function() {
var name = $("input[name=name]").val();
var email = $("input[name=email]").val();
var number = $("input[name=number]").val();
var message = $("textarea[name=message]").val();
if (defaults['name'] == name || name == "") {
$(".error").text("Please enter your name!");
return false;
} else if (defaults['email'] == email || email == "") {
$(".error").text("Please enter your email!");
return false;
} else if (defaults['number'] == number || number == "") {
$(".error").text("Please enter your number!");
return false;
} else if (defaults['message'] == message || message == "") {
$(".error").text("Plese enter your message!");
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&number=' + number + '&message=' + message;
$(".error").text("Please wait...").hide().fadeIn("fast");
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function() {
$('#form form').html("");
$('#form form').append("<div id='success'>Your message has been sent! Thank you</div>");
}
});
return false;
});
And here is the HTML form:
<form id="contact" method="post" action="#">
<label for="name">Name:</label>
<input type="text" name="name" required tabindex="1">
<label for="email">Email adress:</label>
<input type="text" name="email" required tabindex="2">
<label for="number">Tel. number:</label>
<input type="text" name="number" tabindex="3">
<label for="message">Your message:</label>
<textarea name="message" rows="10" cols="70" required tabindex="4"></textarea>
<input type="checkbox" id="terms" name="terms" value="terms">I agree to the terms
<input type="submit" name="submit" class="submit more-info" tabindex="5" value="Send">
<span class="error"></span>
</form>
I have been using the same code for all of my contact forms and it worked all right. Could it be hosting/server related issue?
replace your click event
$(".submit").click(function() {
with
$('.submit').unbind('click').click(function() {
code.
What I can assume your click event is binding two times may be due to a lot of the mess in the code
also use this line in the end of the click event function
$('.submit').unbind('click').click(function() {
// your stuff
event.stopImmediatePropagation(); // as long as not bubbling up the DOM is ok?
});
for reference have a look at the link: https://forum.jquery.com/topic/jquery-executes-twice-after-ajax
$(".submit").click(function(e) { ... }) POSTS to your server for the first time.
Because this is a <submit> button, the form will still submit. The form POSTS to your server for the second time.
The solution would be adding a e.preventDefault() at the bottom inside the $(".submit").click function...
$(".submit").click(function(e) {
// ^ add this e
var name = ...;
$.ajax({
...
});
e.preventDefault();
return false;
});
Try removing the jQuery animations:
$(".error").text("Please wait...").hide().fadeIn("fast");
They can sometimes cause problems.
So I've got this AJAX contact form, the code of which I've used before. I can't work out quite why it isn't working.
HTML
<div id="website-contact-form">
<form id="website_contact" name="website_contact">
<input id="email-address-input" name="website-email" type="text" placeholder="Your email here" class="order-form-input" /><br />
<textarea name="website-message" placeholder="Please give a brief description of what you have in mind, plus contact details." class="order-form-textarea"></textarea>
</form>
</div>
JS
<script type="text/javascript">
$(document).ready(function(){
$('#submit-website-project').click(function (e) {
e.preventDefault();
if ($('#email-address-input').val() != ""){
postForm("ajax/contact-website.php", "website_contact",
function (data) {
if (data == "success") {
$('#website-contact-form').
html("<br />Thankyou for your enquiry. I'll "+
"get in touch shortly.");
} else {
alert("That didn't work. Try again?");
}
});
}
});
}); //END DOCUMENT READY
function postForm(url, form_id, success_func) {
$.ajax({
type: "POST",
url: url,
data: $("#" + form_id).serialize(),
success: function (data) {
success_func(data);
}
});
}
</script>
And finally my PHP
<?php
if (isset($_POST['email'])) {
$_POST['email'] = trim(#$_POST['email']);
$ToEmail = 'barneywimbush:gmail.com';
$EmailSubject = 'Barneywimbush.com';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Email: ".$_POST["email"]."";
$MESSAGE_BODY .= "Comment: ".nl2br($_POST["project_description"])."";
$res = mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader); // or die ("Failure")
if ($res) {
echo "success";
}
else {
echo "failed";
}
}
else {
echo "failed";
}
I'm just getting the alert "That didn't work. Try again?"
Your PHP variables for your $_POSTs are incorrect, on checking the Network panel, your form is sending off,
website-email: yes#test.com
website-message: Test data
Whilst your PHP code is looking $_POST['email'], were it should be $_POST['website-email'];
Change the name attribute of your input elements to change the param name for the request.
I am having trouble getting the email to send which I am sure it is because of the php but here is the js ajax also..it shows my error messages for form fields that are not filled out correctly and then it shows my processing bar once submitted but I get my error message after submission..any help would be appreciated.
html
<form method="post" action="feedback.php" id="contactform">
<fieldset class="first">
<div id="response"></div>
<div id="name_input">
<input id="name" name="name" placeholder="Name" class="required" type="text" maxlength="128" />
</div>
<div id="email_input">
<input id="email" name="name" placeholder="Email" class="required" type="text" maxlength="128" />
</div>
<div id="budget_input">
<label for="budget">Budget</label>
<select id="mydropdown">
<option value="none" selected=“”> -- choose one --</option>
<option value="firstchoice">$0 - $1,000</option>
<option value="secondchoice">$1,000 - $2,000</option>
<option value="thirdchoice">$3,000 +</option>
</select>
</div>
<div id="button">
<input type="submit" class="button" name="Submit" value="" />
</div>
</fieldset>
</form>
Updated:
<?php
$name = trim(stripslashes(htmlspecialchars($_POST['name'])));
$email = trim(stripslashes(htmlspecialchars($_POST['email'])));
$mydropdown = trim(stripslashes(htmlspecialchars($_POST['mydropdown'])));
$recipient = "blake.harrison1#cox.net";
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];
if ($honeypot == 'http://' && empty($humancheck)) {
//Validate data and return success or error message
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";
if (!preg_match($reg_exp, $email)) {
$error_message .= "<p>A valid email address is required.</p>";
}
if (empty($name)) {
$error_message .= "<p>Please provide your name.</p>";
}
if (empty($mydropdown)) {
$error_message .= "<p>Please select an item from the list.</p>";
}
if (!empty($error_message)) {
$return['error'] = true;
$return['msg'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message;
echo json_encode($return);
exit();
} else {
//send to an email
$emailSubject = 'Top Contact Form';
$webMaster = 'blake.harrison1#cox.net';
$body="
<br><hr><br>
<strong>Name:</stong> $name <br>
<br>
<strong>Email:</stong> $email <br>
<br>
<strong>Budget:</strong> $mydropdown <br>
<br>
";
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
//send email and return to user
if(mail($webMaster, $emailSubject, $body, $headers)) {
$return['error'] = false;
$return['msg'] = "<p>Message sent successfully. Thank you for your interest " .$name .".</p>";
echo json_encode($return);
}
}
} else {
$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";
echo json_encode($return);
}
?>
$(document).ready(function() {
$('form #response').hide();
$('#submit').click(function(e) {
// prevent forms default action until
// error check has been performed
e.preventDefault();
// grab form field values
var valid = '';
var required = ' is required.';
var name = $('form #name').val();
var email = $('form #email').val();
var mydropdown = $('form #mydropdown').val();
var honeypot = $('form #honeypot').val();
var humancheck = $('form #humancheck').val();
// perform error checking
if (name == '' || name.length <= 2) {
valid = '<p>Your name' + required +'</p>';
}
if (!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>Your email' + required +'</p>';
}
if (mydropdown == '') {
valid += '<p>An item from the list' + required +'</p>';
}
if (honeypot != 'http://') {
valid += '<p>Spambots are not allowed.</p>';
}
if (humancheck != '') {
valid += '<p>A human user' + required + '</p>';
}
// let the user know if there are erros with the form
if (valid != '') {
$('form #response').removeClass().addClass('error')
.html('<strong>Please correct the errors below.</strong>' +valid).fadeIn('fast');
}
// let the user know something is happening behind the scenes
// serialize the form data and send to our ajax function
else {
$('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('slow');
var formData = $('form').serialize();
submitForm(formData);
}
});
});
function submitForm(formData) {
$.ajax({
type: 'POST',
url: 'send.php',
data: formData,
dataType: 'json',
cache: false,
timeout: 12000,
success: function(data) {
$('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).fadeIn('fast');
if ($('form #response').hasClass('success')) {
setTimeout("$('form #response').fadeOut('fast')", 12000);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('form #response').removeClass().addClass('error')
.html('<p>There was an<strong> ' + errorThrown +
'</strong> error due to a<strong> ' + textStatus +
'</strong> condition.</p>').fadeIn('fast');
},
complete: function(XMLHttpRequest, status) {
$('form')[0].reset();
}
});
};
can you try $.post instead of $.ajax
$.post(url, {argument_name: value, ...} , function(data){
// callback function..
}, 'json'}
do this with the php page...
sleep(2);
//Sanitize incoming data and store in variable
$name = trim(stripslashes(htmlspecialchars($_POST['name'])));
$email = trim(stripslashes(htmlspecialchars($_POST['email'])));
$message = trim(stripslashes(htmlspecialchars($_POST['message'])));
$recipient = "info#internetmarketingtrio.com";
//Validate data and return success or error message
$errors = array();
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";
if (!preg_match($reg_exp, $email)) {
$errors[] = "<p>A valid email address is required.</p>";
}
if (empty($name) || $name == '') {
$errors[] = "<p>Please provide your name.</p>";
}
if (empty($message) || $message == '') {
$errors[] = "<p>A message is required.</p>";
}
if(empty($errors)) {
$return['success'] = true;
$return['message'] = "<p>Thanks for your feedback " .$name. ".</p>";
} else {
$return['success'] = false;
$return['message'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>";
foreach($errors as $error) {
$return['message'] .= $error ."<br />";
}
}
And then in your call to get this page... the ajax call...
$.ajax({
type: 'POST',
url: 'feedback.php',
data: formData,
dataType: 'json',
cache: false,
success: function(data) {
if(data.success) {
$("form#response").removeClass().addClass('success').html(data.message).fadeIn('fast');
removeResponse(5000);
} else {
$("form#response").removeClass().addClass('error').html(data.message).fadeIn('fast');
}
}
});
function removeResponse(time) {
setTimeout(function() {
$("form#response").fadeOut('fast');
}, time);
}
And that should do ya
adding this to the bottom of my php ended up fixing my issue if anyone reads this
$emailSubject = 'Contact Form';
$webMaster = 'blake.harrison1#cox.net';
$body="
<br><hr><br>
<strong>Name:</stong> $name <br>
<br>
<strong>Email:</stong> $email <br>
<br>
<strong>Message:</stong> $message
";
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
//send email and return to user
if(mail($webMaster, $emailSubject, $body, $headers)) {
$return['error'] = false;
$return['msg'] = "<p>Message sent successfully. Thank you for your intrest " .$name .".</p>";
echo json_encode($return);
}
}
} else {
$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";
echo json_encode($return);
}
?>
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>