I am attempting to create an ajax contact form that the results gets emailed to me. I found a form demo online and edited it to meet my criteria, except that there were no checkboxes in the demo, when I add checkboxes everything but those work.
Can someone please guide me through this?
The html is:
<div class="done">
<strong>Thank you !</strong> We've received your questions and someone from our office will respond at our earliest convience.</p>
<p>Check your email, we just sent you a coupon for 10% off your first purchase.</p>
</div>
<div class="form">
<form method="post" action="process2.php" autocomplete="off">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<ul>
<li>Design:</li>
<li><label for="master_plan"><input type="checkbox" name="service[]" id="master_plan" value="Master Plan" /> Master Plan</label></li>
<li><label for="front_foundation"><input type="checkbox" name="service[]" id="front_foundation" value="Front Foundation" /> Front Foundation</label></li>
<li><label for="backyard_plan"><input type="checkbox" name="service[]" id="backyard_plan" value="Backyard Plan" /> Backyard Plan</label></li>
<li><label for="specialty_garden"><input type="checkbox" name="service[]" id="specialty_garden" value="Specialty Garden" /> Specialty Garden</label></li>
</ul>
<label for="newsletter"><input type="checkbox" name="newsletter" id="newsletter" value="x" checked="checked" /> Yes, I would like to be added to your newsletter list.</label>
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="5" cols="40" /></textarea>
<input type="submit" id="submit" value="Sign Up" />
<div class="loading"></div>
</form>
</div>
The javascript is:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var comments = $('textarea[name=comments]');
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&comments=' + encodeURIComponent(comments.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "process2.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
$('.form').fadeOut('slow');
$('.done').fadeIn('slow');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
return false;
});
});
</script>
And the php (process2.php) is:
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ?$_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$mailing = ($_GET['newsletter']) ?$_GET['newsletter'] : $_POST['newsletter'];
$comments = ($_GET['comments']) ?$_GET['comments'] : $_POST['comments'];
if($phone) {$phone = '('.substr($phone, 0, 3).') '.substr($phone, 3, 3).'-'.substr($phone, 6, 4);} else {$phone = '(Not Entered)';}
I am so very confused that I dont know what to do?
You aren't including them in your data that you're sending via ajax. You're also not even trying to get the service values in your php.
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&comments=' + encodeURIComponent(comments.val());
//data only includes name, phone, email, comments
You might want to try jQuery serialize method instead of the above code.
var data = $(this).parents('form').serialize();
Related
I have tried everything to get this form to work but no luck.
I guess abide is working now but my php is not sending the email. I don't even think that my php is getting called anyway.
my code is below
form code
line 434
<form id="myForm" data-abide action="mail.php" method="post">
<div class="contactform">
<div class="item item-pair">
<label for="name">Full Name
<input type="text" name="name" id="name" class="small-input cat_textbox" required pattern="[a-zA-Z]+" maxlength="255">
<small class="error small-input">Name is required and must be a string.</small>
</label>
<label for="email">Email Address
<input type="text" name="email" id="email" class="small-input cat_textbox" maxlength="255" required >
<small class="error small-input">An email address is required.</small>
</label>
</div>
<div class="item">
<label>Comments</label>
<textarea cols="10" name="message" id="message" rows="4" class="cat_listbox" required ></textarea>
<small class="error">Please enter your comments</small>
</div>
<div class="item">
<input class="button alert small" type="submit" value="Submit" id="catwebformbutton">
</div>
</div>
</form>
javascript code
line 627
<script>
$('#myForm').submit(function(e) {
//prevent default form submitting.
e.preventDefault();
$(this).on('valid', function() {
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for reponse
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"mail.php",
data: dataString,
success: function(data){
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<h2>Thanks!</h2>")
.append("<p>Dear "+ name +", I will get back to you as soon as I can ;)</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
});
</script>
html link
http://tayrani.com
Please help
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["message"];
$msg = "
Name:$name
Email:$email
Comment:
$comments";
$to = "tayrani#hotmail.com";
$subject = "website email";
$message = $msg;
$headers = "form";
mail($to,$subject,$message,$headers);
?>
Thanks for the help I got it working. It turned out to be Hotmail that is not accepting emails for some reason. So, I replaced the Hotmail account with a Gmail account and it worked. I also updated my code with the following
html code for the form
<form id="myForm" data-abide="ajax" action="mail.php" method="post">
<div class="contactform">
<div class="item item-pair">
<label for="name">Full Name
<input type="text" name="name" id="name" class="small-input cat_textbox" required pattern="[a-zA-Z]+" maxlength="255">
<small class="error small-input">Name is required and must be a string.</small>
</label>
<label for="email">Email Address
<input type="email" name="email" id="email" class="small-input cat_textbox" maxlength="255" required >
<small class="error small-input">An email address is required.</small>
</label>
</div>
<div class="item">
<label>Comments</label>
<textarea cols="10" name="message" id="message" rows="4" class="cat_listbox" required ></textarea>
<small class="error">Please enter your comments</small>
</div>
<div class="item">
<input class="button alert small" type="submit" value="Submit" id="catwebformbutton" name="btnSubmit">
</div>
</div>
</form>
My javascript code including fixing the submitting twice issue
<script>
$('#myForm').submit(function(e) {
//prevent default form submitting so it can run the ajax code first
e.preventDefault();
$(this).on('valid', function() { //if the form is valid then grab the values of these IDs (name, email, message)
var name = $("input#name").val();
var email = $("input#email").val();
var message = $("textarea#message").val();
//Data for reponse (store the values here)
var dataString = 'name=' + name +
'&email=' + email +
'&message=' + message;
//Begin Ajax call
$.ajax({
type: "POST",
url:"mail.php", //runs the php code
data: dataString, //stores the data to be passed
success: function(data){ // if success then generate the div and append the the following
$('.contactform').html("<div id='thanks'></div>");
$('#thanks').html("<br /><h4>Thanks!</h4>")
.append('<p><span style="font-size:1.5em;">Hey</span> <span class="fancy">'+ name +'</span>,<br />I´ll get back to you as soon as I can ;)</p>')
.hide()
.fadeIn(1500);
},
error: function(jqXHR, status, error){ //this is to check if there is any error
alert("status: " + status + " message: " + error);
}
}); //End Ajax call
//return false;
});
});
</script>
<script>
$(document).foundation('abide', 'events'); // this was originally before the above code, but that makes the javascript code runs twice before submitting. Moved after and that fixes it.
</script>
Here is the php code
<?php
if(isset($_POST["name"])){
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["message"];
$msg = "
Name: $name
Email: $email
Comments:
$comments";
$to = "h2hussein#gmail.com";
$subject = "Tayrani.com Contact Form";
$headers = "From: <$email>";
mail($to,$subject,$msg,$headers);
}else{
}
?>
I struggled for 3 days to get this done but thanks to my colleague/friend Adam as he really helped me with it.
I hope this is useful for other people.
Thanks,
Hussein
tayrani.com
I am making a ajax form. I get the success message but I dont get any email, any thoughts?
send-form.php:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text']) && isset($_POST['email'])) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
//send email
mail( "mymail#email.com", "Contact Form: ".$_POST['name'], $_POST['text'], "From:" . $_POST['email'] );
}
?>
functions.js:
$(function() {
// Contact Form
$("#contact").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var text = $("#text").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text;
$("#contact").validate({
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "send-form.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
}
})
return false;
});
});
index.html:
<form id="contact" method="post">
<fieldset>
<label>Your Name</label><br />
<input name="name" id="name" type="text">
<label>Your Email</label><br />
<input name="email" id="email" type="text">
<label>Your Question</label><br />
<textarea rows="10" name="text" id="text" ></textarea>
</fieldset>
<input type="submit" value="Send Message" name="submit">
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</form>
I have been siting with this in hours, trying to edit it with my own skill, but no success. This is what I got so far. I am getting the success message but no email sent to me.
Any Help is appreciated!
I'm making a ajax call to a server side function to send an email. It works fine. My issue is before sending the email i need to validate the captcha where the server side code resides in CaptchaValidation.php. If i call "CaptchaValidation.php" on form action it should work fine but here since i'm doing a ajax call i need to use e.preventDefault();. So that form action is not working.
How can i make it work?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divLoading').hide();
$('#appointment').submit(function (e) {
e.preventDefault();
var serviceURL = 'WebService.asmx/SendMail';
var Name = $("#fname").val();
var Email = $("#email").val();
var Telephone = $("#phone").val();
var Comment = $("#comment").val();
if ($("#fname").val().length == 0) {
alert("Please Enter Name");
$("#fname").focus();
return false;
}
if ($("#email").val().length == 0) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf("#") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf(".") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
$('#divLoading').show();
$.ajax({
type: "POST",
url: serviceURL,
data: '{"name":"' + Name + '","address":"' + Email + '","telephone":"' + Telephone + '","comment":"' + Comment + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
// alert("Mail Sent!");
$('#divLoading').hide();
window.location = "contat-submit.php";
}
function errorFunc() {
// alert('error');
}
});
});
</script>
</head>
<body>
<form name="appointment" id="appointment" method="post" action="CaptchaValidation.php">
<div>
</div><div id="leftcolumn4"><div class="h2">Contact Form</div>
<form name="appointment" id="Form1" method="post" action="send_contact.php">
Full Name:
<br />
<label>
<input name="fname" type="text" class="form-input" id="fname" size="30" />
</label>
<br /><br />
Email Address:<br />
<label>
<input name="email" type="text" class="form-input" id="email" size="30" />
</label><br /><br />
Telephone:
<br />
<label>
<input name="phone" type="text" class="form-input" id="phone" size="30" />
</label>
<br /><br />
Your Comment:<br />
<label>
<textarea name="comment" cols="28" rows="4" class="form-input-box" id="comment"></textarea><br />
<br />
</label><input name="submit" type="submit" class="form-input-submit" value="Submit" id="btnMail"/>
</div>
</form>
</body>
</html>
Follow the steps:
Change the Submit button to a simple button so that on click of that button the form will not submit.
On Click of that button call a function which will have call e.preventDefault();
function callSubmit() {
// do ajax call
}
You are doing ajax call in e.preventDefault() function. So in AJAX response, you have to check if the AJAX response is correct then do a form submit using:
$('#appointment').submit()
Now just remove the e.preventDefault(); function from you form.submit function you have written. This will allow to AJAX submit and send email.
I'm following the following tutorial to place a form on my website using PHP, AJAX, and JQUERY that will send the form information to my email:
http://www.spruce.it/noise/simple-ajax-contact-form/
The problem is, when I have the jquery outside the document ready I get no message at all, and when I place it in the document ready i get the error text, but when there is information in the fields nothing happens at all. Please, can someone look and see what might be the problem with my html, jquery, php, or AJAX? I'm about to pull out all of my hair. I'm testing it in Wampserver.
The HTML file is in the root directory with the PHP file. In the root directory there is a folder called "includes" that the Javascript is in. Here is the relevant code for each:
HTML:
<form id="repairform" method="post">
<p id="p1">Name:</p>
<input id="one" type="text" name="name" />
<p id="p2">How would you prefer to be reached?: </p>
<select id="two" name="Contact methods">
<option value="Phone">Email</option>
<option value="Email">Phone</option>
</select>
<p id="p3">What kind of computer are you having trouble with?</p>
<p id="p3-2">Give as much or as little info. as you'd like.</p>
<p id="p3-3">(Laptop PC, desktop Macintosh, etc)</p>
<textarea id="four" name="pc type" rows="3" cols="30"></textarea>
<p id="p4">What problems are you having with your computer/ what needs to be fixed?</p>
<textarea id="five" name="problem" rows="5" cols="30"></textarea>
<input id="three" type="submit" value="Submit Request" />
<p id="p5">What is your Email?</p>
<input id="six" type="text" name="Email/Phone" />
<p id="p7">What is your Phone Number?</p>
<input id="eight" type="text" name="Email/Phone2" />
<p id="p6">What time of day would you prefer to be reached?</p>
<input id="seven" type="text" name="Preferred Contact Time" />
</form>
JQuery:
$(document).ready(function () {
$("#repairform").submit(function (e) {
e.preventDefault();
if (!$("#six").val()) {
$("#six").val("shanew#ufl.edu");
}
var name = $("#one").val();
var email = $("#six").val();
var text = $("#five").val();
var reachpreference = $("#two").val();
var computertype = $("#four").val();
var phonenumber = $("#eight").val();
var timeofday = $("#seven").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text
+ '&reachpreference=' + reachpreference + '&computertype=' + computertype
+ '&phonenumber=' + phonenumber + '&timeofday=' + timeofday;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (text.length > 2) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "../functions.php",
data: dataString,
success: function () {
alert("Thank you! Your message has been delivered. I will be back with you shortly");
}
});
} else {
alert("Some of the form information was not filled out correctly. Ensure all of the correct fields are filled out.");
}
return false;
});
PHP:
<?php
// Email Submit
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text'])){
//send email
mail("shanew#ufl.edu", "Contact Form: ".$_POST['name'],
$_POST['text'], $_POST['reachpreference'], $_POST['computertype']
$_POST['phonenumber'], $_POST['timeofday'], "From:" . $_POST['email']);
}
?>
Use
data: $('#repairform').serializeArray()
instead of the datastring object you're creating.
The datastring will be treated as a String, and you'll never be able to access it using $_POST['text'] and all. You may try using using $_GET instead. The datastring will be accessible that way only.
I think you miss some of closing branch });
And I think you should use name attribute for variable name that will be used in php..
<form id="theForm">
<input type="text" name="email" />
</form>
and in javascript you can use serialize so less line and easier to read.
$.ajax({
type:'POST'
url:'../functions.php'
data:$('#theForm').serialize();
})
and in php
echo $_POST['email']
jquery ajax form: loading image only and doesnt stop and success message not working
this is my contact form
<form method="post" action="" class="comments-form" id="contactform" />
<p class="input-block">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p class="input-block">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p class="input-block">
<label for="message">Message:</label>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</p>
<p class="input-block">
<button class="button default" type="submit" id="submit">Submit</button>
</p>
</form>
and this is my jquery ajax function that is not working
(function() {
if($('#contactform').length) {
var $form = $('#contactform'),
$loader = '<img src="images/preloader.gif" alt="Loading..." />';
$form.append('<div class="hidden" id="contact_form_responce">');
var $response = $('#contact_form_responce');
var $p
$response.append('<p></p>');
$form.submit(function(e){
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $("#contactform").serialize()
};
//send data to server
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
if(response.is_errors){
$response.find('p').removeClass().addClass("error type-2");
$.each(response.info,function(input_name, input_label) {
$("[name="+input_name+"]").addClass("wrong-data");
$response.find('p').append('Please enter correctly "'+input_label+'"!'+ '</br>');
});
} else {
$response.find('p').removeClass().addClass('success type-2');
if(response.info == 'success'){
$response.find('p').append('Your email has been sent!');
$form.find('input:not(input[type="submit"], button), textarea, select').val('').attr( 'checked', false );
$response.delay(1500).hide(400);
}
if(response.info == 'server_fail'){
$response.find('p').append('Server failed. Send later!');
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $form.offset().top + $form.outerHeight() - $(window).height();
if($(document).scrollTop() < bottomPosition) {
$('html, body').animate({
scrollTop : bottomPosition
});
}
if(!$('#contact_form_responce').css('display') == 'block') {
$response.show(450);
}
});
e.preventDefault();
});
}
})();
and this is my contact-send.php that saves the message in my database.
require_once "../includes/database.php";
$cname=$_POST['name'];
$cemail=$_POST['email'];
$cmessage=$_POST['message'];
$date=date("Y-m-d");
$sql = "INSERT INTO messages (sendername,senderemail,message,datesent) VALUES (:name,:email,:message,:date)";
$qry = $db->prepare($sql);
$qry->execute(array(':name'=>$cname,':email'=>$cemail,':message'=>$cmessage,':date'=>$date));
I think your issue is here:
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
//--^--------------------------------------missing '$'
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
//----^------------------------------------used the '$' for other codes
try to put a $ here and see if this solves the issue:
$response = $.parseJSON(response);
and if you are getting some ajax errors plz mention it.