I have 3 contact form in one page ( Header, Body, Footer ). The code works correctly if sent from one form. I want to use one AJAX request for all forms. That is, when you click on the submit button, so that the code checks if this form then send data to php. How can i do it right? I use the hasClass () method of jquery, but I have errors in the console
HTML:
Footer Form
<form id="contact-form1" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="name" placeholder="Name">
<input type="text" class="simple-input" id="email" placeholder="Email address">
<textarea class="quession-input" id="msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" class="checked-checkbox" name="myCheckboxes[]" id="box1" checked="checked" value="true" />
<label for="box1" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn submit1"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
Another Form
<form id="contact-form" method="POST" class="d-flex form">
<input type="text" class="simple-input" id="hy_name" placeholder="Name">
<input type="text" class="simple-input" id="hy_email" placeholder="Email address">
<textarea class="quession-input" id="hy_msg" placeholder="Your question"></textarea>
<div class="checkboks custom-sq">
<input type="checkbox" id="box3" class="checked-checkbox" checked="checked" />
<label for="box3" class="checkboks-text"><?php echo the_field('checkbox_text', 'option'); ?></label>
</div>
<button type="submit" id="submit" class="danger-btn hy-submit submit2"><?php echo the_field('btn_send', 'option'); ?></button>
</form>
jQuery:
jQuery('#submit').on('click', function(e) {
e.preventDefault();
if(e.hasClass('submit1')) {
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var msg = jQuery('#msg').val();
var subj = jQuery('#subj').val();
var data = "action=send_email&name=" + name + "&email=" + email + "&msg=" + msg + "&subj=" + subj + "&myCheckboxes=" + choice,
} elseif (e.hasClass('submit2')) {
var hy_name = jQuery('#hy_name').val();
var hy_email = jQuery('#hy_email').val();
var hy_msg = jQuery('#hy_msg').val();
var data = "action=send_email&name=" + hy_name + "&email=" + hy_email + "&msg=" + hy_msg + "&myCheckboxes=" + choice,
}
validateEmail(email);
if (msg == '' || email == '' || validateEmail(jQuery('#email').val()) == false) {
validateEmail(email);
validateText(jQuery('#msg'));
validateText(jQuery('#name'));
return false;
}
var chkElem = document.getElementsByName("myCheckboxes[]");
var choice ="";
for(var i=0; i< chkElem.length; i++)
{
if(chkElem[i].checked)
choice = choice + chkElem[i].value;
}
jQuery.ajax({
type: "post",
url: "/wp-admin/admin-ajax.php",
data: data;
success: function (response) {
jQuery('#contact-form input').val('');
jQuery('#contact-form textarea').val('');
jQuery('.submit').text('Done!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
});
PHP:
add_action('wp_ajax_nopriv_send_email', 'send_email');
add_action('wp_ajax_send_email', 'send_email');
function send_email() {
$checkbox = $_POST['myCheckboxes'];
if (isset($checkbox)) {
echo $checkbox;
}
$headers = 'Content-Type: text/html; charset="utf-8"';
$name = $_POST['name'];
$hy_name = $_POST['hy_name'];
$from = 'contact#xelon.ch';
$to = 'yaver.mammadov#gmail.com';
$email = $_POST['email'];
$hy_email = $_POST['hy_email'];
$msg = $_POST['msg'];
$hy_msg = $_POST['hy_msg'];
$subject = 'Footer form: ' . $_POST['email'];
$message .= (!empty($name)) ? '<p><strong>User Name</strong> : ' . $name .' </p>' : '';
$message .= (!empty($email)) ? '<p><strong>User Email</strong> : '. $email .'</p>' : '';
$message .= (!empty($msg)) ? '<p><strong>User Message</strong> : '.$msg .'</p>' : '';
$message .= (!empty($checkbox)) ? '<p><strong>Checkboxs</strong> : '.$checkbox .'</p>' : '';
$message .= '</body></html>';
echo mail($to, $subject, $message, $headers);
return $msg;
die();
}
You can use method serialize(), and use a class to identifique buttons submit. Using two identical ids on one page is not good practice.
If you use the class .submit per example in each button submit:
$('.submit').on('click', function(e) {
e.preventDefault();
var data = $(this).closest('form').serialize();
[...]
}
Related
I am trying to validate a captcha code field so if the code they enter is correct it will take them to a thank you page with the download link, but if the security code they entered is incorrect then they will see a sorry message and to return back to previous page.
The issue I am facing is when I enter the captcha into this field and click submit the data is always no.
My form is a as follows:
<form action="" name="downloadform" id="downloadform" class="downloadform" method="post">
<div class="field">
<input name="name" type="text" id="name" class="input name" placeholder="Name..." />
</div>
<div class="field">
<input name="company" type="text" id="company" class="input company" placeholder="Company..." />
</div>
<div class="field">
<input name="tel" type="text" id="tel" class="input tel" placeholder="Telephone..." />
</div>
<div class="field">
<input name="email" type="text" id="email" class="input email" placeholder="Email Address..." />
</div>
<div class="field">
<img src="/CaptchaSecurityImages.php" alt="Captcha" class="captcha" />
<input type="text" name="sec_code" id="sec_code" class="input sec_code" placeholder="Please enter the characters above" />
</div>
<div class="field">
<div class="medium secondary btn"><input type="submit" name="Submit2" value="Send Request" class="btn" id="downloadbtn" /></div>
<input type="hidden" name="product" id="product" class="product" value="<?php echo $page[3]; ?>" />
</div>
</form>
My ajax form file looks like this:
$(function() {
filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$("#downloadbtn").click(function() {
var name = $("#name").val();
var company = $("#company").val();
var tel = $("#tel").val();
var email = $("#email").val();
var product = $("#product").val();
var sec_code = $("#sec_code").val();
if (name == "") {
$("#name").focus();
$("#name").val("");
$("#name").css({background:"#b72a18", color:"#fff"});
return false;
}
if (company == "") {
$("#company ").focus();
$("#company ").val("");
$("#company ").css({background:"#b72a18", color:"#fff"});
return false;
}
if (tel == "") {
$("#tel").focus();
$("#tel").val("");
$("#tel").css({background:"#b72a18", color:"#fff"});
return false;
}
if (!filter.test(email)) {
$("#email").focus();
$("#email").val("");
$("#email").css({background:"#b72a18", color:"#fff"});
return false;
}
if (product == "") {
$("#product").focus();
$("#product").val("");
$("#product").css({background:"#b72a18", color:"#fff"});
return false;
}
if (sec_code == "") {
$("#sec_code").focus();
$("#sec_code").val("");
$("#sec_code").css({background:"#b72a18", color:"#fff"});
return false;
}
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>');
var dataString = '&name=' + name + '&tel=' + tel + '&company=' + company + '&email=' + email + '&product=' + product + '&sec_code=' + sec_code + '&type=download';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/process_download.php",
data: dataString,
datatype: 'json',
success: function(data) {
$('.downloadform').html('<center><img src="/images/ajax-loader.gif" style="padding:20px;"></center>')
.hide()
.fadeIn(1500, function() {});
setTimeout(function ()
{
$(window.location).attr('href', '/process.php?download=' + data.product + '&sec_code=' + data.sec_code);
}, 2000);
}
});
return false;
});
});
Then I have my process download file:
<?php
session_start();
header("Content-type: application/json");
ob_start();
include('inc/connection.php');
$product = $_POST['product'];
$sec_code = $_SESSION['security_code'] == $_POST['sec_code'] ? 'yes' : 'no';
ob_end_clean();
$data = array('product'=>$product,'sec_code'=>$sec_code);
print json_encode($data);
die();
?>
Then the final process:
<?php
session_start();
include('inc/connection.php');
$sec_code = $_GET['sec_code'];
$proddownlink = $_GET['download'];
$proddownl = str_replace("_", " ", $_GET['download']);
$proddownl = ucwords($proddownl);
if ($sec_code == 'no') {
$message = '<p>Security code is wrong. Please click here to return back.</p>';
} else {
$message = '<p>Thank you for downloading ' . $proddownl . ' Data Sheet.</p>
<p>Please click here to download ' . $proddownl . ' PDF.</p>';
include_once('inc/connection.php');
include_once('inc/class.phpmailer.php');
$name = $_POST['name'];
$company = $_POST['company'];
$tel = $_POST['tel'];
$email = $_POST['email'];
$product = $_POST['product'];
$sec_code = $_POST['sec_code'];
$type = $_POST['type'];
$bodytext = "<ul>
<li><strong>Name:</strong> $name</li>
<li><strong>Company:</strong> $company</li>
<li><strong>Telephone Number:</strong> $tel</li>
<li><strong>Email Address:</strong> $email</li>
<li><strong>Area of Interest:</strong> $product</li>
</ul>";
$subject = "New Enquiry";
$query = "insert into user_email set name = '$name', email = '$email', tel = '$tel', type = '$type', message = '$bodytext'";
$result = $conn->query($query);
if(!$result) die($conn->error);
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $bodytext;
$mail->From = "sales#fidelitysystems.co.uk";
$mail->FromName = $name;
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
#$mail->AddAddress("sales#fidelitysystems.co.uk");
$mail->AddAddress("craig#arrivaldesign.co.uk");
$mail->IsSMTP();
$mail->SMTPAuth = "true";
$mail->Username = "postmaster#arrivalbusiness.co.uk";
$mail->Password = "edward";
$mail->Host = "mail.arrivalbusiness.co.uk";
$mail->Port = 587;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
?>
I have a problem when sending data to the contact form. Data is sent to e-mail only if you click many times, but if you tab to move to the button and press enter data is sent immediately. But still fall into the spam.
HTML
<div id="f1" class="contact_wrapper">
<form>
<div id="r2"></div>
<input type="text" name='rname' id="names" class="name" placeholder="Ваше имя">
<input type="email" name='email' id="eml" class="email" placeholder="Ваше Email">
<input type="text" name='subject' id="phon" class="contact_number" placeholder="Контактный телефон">
<textarea name="message" id="masage" cols="30" rows="10"></textarea>
<input name="" id="button" type="button" value="Отправить" class="submit" onclick="mail2('Радиус-01 Оформить заявку - последняя форма','names','eml','phon','masage','f1','r2')">
</form>
</div>
AJAX
<script>
function mail2(subject,names,eml,phon,masage,f,rr){
var names = document.getElementById(names).value;
var eml = document.getElementById(eml).value;
var phon = document.getElementById(phon).value;
var masage = document.getElementById(masage).value;
var frt = document.getElementById('generator_konr').value;
var params = {subject:subject,names:names,eml:eml, phon:phon,masage:masage,kon:frt};
$.ajax({
type: "POST",
url: "mail2.php",
data: params,
success: function(data){
$('#ertretgfdg').html(data).fadeIn("slow");
}
});
}
</script>
mail2.php
<?
### Referals script start
$debug=0;
function writelog($s) {
global $lf,$debug;
if ($debug)
fputs($lf,"$s\n");
}
if ($debug)
$lf=#fopen(dirname(__FILE__).'/'.'debug.log','a');
$t=date('Y-m-d H:i:s');
$utm='нет';
$term='нет';
$ip=$_SERVER['REMOTE_ADDR'];
$utmdata='';
writelog("Session started (zakaz.php) at '$t', IP='$ip'");
writelog("REQUEST: ".print_r($_REQUEST,true));
if (isset($_COOKIE['utmdata'])) {
writelog("Found saved cookie UTMdata");
$utmdataexp=explode('&',$_COOKIE['utmdata']);
if (count($utmdataexp)>=2 && !empty($utmdataexp[0]) && !empty($utmdataexp[1])) {
$t=$utmdataexp[0];
$utm=$utmdataexp[1];
$term=isset($utmdataexp[2]) ? $utmdataexp[2] : 'нет';
$utmdata=$t.'&'.$utm.'&'.$term;
}
}
writelog("UTMdata is '$utmdata'");
### Referals script end
$phon = $_POST['phon'];
$names = $_POST['names'];
$subject = $_POST['subject'];
$kon = $_POST['kon'];
$eml = $_POST['eml'];
$masage = $_POST['masage'];
if ($names=='' or $names=='Введите ваше имя') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите свое имя");</script>';
exit;
}
if ($phon=='' or $phon=='Ваш телефон' or $phon=='Введите номер телефона') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите номер телефона");</script>';
exit;
}
if ($eml=='' or $eml=='Ваш email' or $eml=='Введите ваш email') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваш email");</script>';
exit;
}
if ($masage=='' or $masage=='Ваше сообщение' or $masage=='Введите ваше сообщение') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваше сообщение");</script>';
exit;
}
$er=null;
if ($subject=='Выбран конкретный генератор') {
$ert='Генератор: '.$kon.'<br/>';
}
$body ='
По вопросу: '.$subject.'<br/>
'.$ert.'
Имя: '.$names.'<br/>
Телефон: '.$phon.'<br/>
Мыло: '.$eml.'<br/>
Сообщение: '.$masage.'<br/>
Рекламная площадка:</b> '.$utm.'<br />
Ключевое слово: '.$term.'<br />
';
$email='myemail#gmail.com';
$headers = "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: <".$em.">\r\n";
if (mail($email, $subject_t, $body, $headers)) {
echo '<script>$().toastmessage(\'showSuccessToast\', "Сообщение успешно отправлено");</script>
<script>$(".header .sform").delay( 2000 ).slideToggle();</script>';
exit;
} else {
echo '<script>$().toastmessage(\'showErrorToast\', "Ошибка, повторите попытку");</script>';
exit;
}
?>
<!--
I've a simple working php/ajax contact form with validation. I'd like to clear all fields after VALID submission, so I tried $("#myform")[0].reset(); see in the code below. It clears the form nicely, but the problem is it also clears everything when the validation wasn't successful, which is really annoying.
Here's the HTML:
<form id="myform" method="post" action="sendEmail.php">
<div id="container">
<div id="main">
<p>Name / Company <span>*</span></p>
<input type="text" name="name" id="name" />
<p>Email Address <span>*</span><p>
<input type="text" name="email" id="email" />
<p>Offer / Message <span>*</span></p>
<textarea name="message" id="message" rows="6"></textarea>
<p><input type="submit" name="submit" id="submit" value="Send Request" /></p>
<p><ul id="response" /></p>
</div>
</div>
And the php:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$message = $_POST['message'];
$site_owners_email = 'sample#yahoo.com';
$site_owners_name = 'Joe';
if (strlen($name) < 3) {
$error['name'] = "* Please enter your name.";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "* Please enter a valid email address";
}
if (strlen($message) < 4) {
$error['message'] = "* Please leave an offer / message.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Subject";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Send();
echo "<li class='success'> Thanks for your request!<br> We will respond to you as soon as possible. </li>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['message'])) ? "<li>" . $error['message'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
At last, the js:
$(function() {
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Send Request" />');
$('#main input#submit').click(function() {
$('#main').append('<img src="images/ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var name = $('input#name').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'sendEmail.php',
data: 'name=' + name + '&email=' + email + '&message=' + message,
success: function(results) {
$('#main img.loaderIcon').fadeOut(1000);
$('ul#response').html(results);
$("#myform")[0].reset();
}
}); // end ajax
});
});
I'm new to php and js, so I've pasted all of my code, to be easier for you if i did something wrong. Thanks for your help!
Well, a good idea is returning a JSON object form PHP, so you can check for errors on Javascript.
PHP:
$result = array(
"error" => false,
"html" => null
);
if(!$is_valid){
$result["error"] = true;
$result["html"] = "<b>Error</b>";
}else{
$result["error"] = false;
$result["html"] = "<b>Success</b>";
}
echo json_encode($result);
jQuery
$.ajax({
type: 'post',
url: 'url.php',
data: {/*put a cool data here*/},
dataType : "json", // return a json object
success: function(result) {
if(result.error){
/* On error stuff */
$("body").append(result.html);
}else{
/* On success stuff */
$("body").append(result.html);
}
}
});
Hi really need some help...
First of all I know very little of jQuery / javascript, I learnt basic CSS a month back after having a website professionally built, then basic HTML, a few days ago I thought I would try my luck with jQuery but I am a total novis so if you answer please keep in mind I know almost nothing about these things - thanks!
I have been trying to make a new contact form, I have used bits of code from all over the net (so I know the code is probably very messy) anyway the resulting form seems to work fine in Chrome but in IE or FF or Safari on the submit it returns the 'Sorry, there has been a problem with this form' alert and nothing happens, I guess the PHP script is returning '1' to make this happen, but to be honest I am in over my head!
Below is the jquery....
$(function(){
//original field values
var field_values = {
//id : value
'firstname' : 'first name',
'lastname' : 'last name',
'email' : 'email address',
'phone' : 'phone number',
};
//inputfocus
$('input#lastname').inputfocus({ value: field_values['lastname'] });
$('input#firstname').inputfocus({ value: field_values['firstname'] });
$('input#email').inputfocus({ value: field_values['email'] });
$('input#phone').inputfocus({ value: field_values['phone'] });
//reset progress bar
$('#progress').css('width','0');
$('#progress_text').html('0% Complete');
//second_step
$('form').submit(function(){ return false; });
$('#submit_second').click(function(){
//remove classes
$('#second_step input').removeClass('error').removeClass('valid');
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var fields = $('#second_step input[type=text]');
var error = 0;
fields.each(function(){
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
//update progress bar
$('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
//slide steps
$('#second_step').slideUp();
$('#third_step').slideDown();
} else return false;
});
$('#submit_third').click(function(){
//update progress bar
$('#progress_text').html('100% Complete');
$('#progress').css('width','339px');
//prepare the fourth step
var fields = new Array(
$('#firstname').val() + ' ' + $('#lastname').val(),
$('#email').val(),
$('#phone').val(),
$('#service').val(),
$('#location').val(),
$('#mirror').val(),
$('#from').val()
);
var tr = $('#fourth_step tr');
tr.each(function(){
//alert( fields[$(this).index()] )
$(this).children('td:nth-child(2)').html(fields[$(this).index()]);
});
//slide steps
$('#third_step').slideUp();
$('#fourth_step').slideDown();
});
$('#submit_fourth').click(function(){
//Get the data from all the fields
var firstname = $('input[name=firstname]');
var email = $('input[name=email]');
var lastname = $('input[name=lastname]');
var phone = $('input[name=phone]');
//organize the data properly
var data = 'firstname=' + firstname.val() + '&email=' + email.val() + '&lastname=' + lastname.val() + '&phone=' + phone.val() + '&service=' + $('select#service option:selected').val() + '&location=' + $('select#location option:selected').val() + '&mirror=' + $('select#mirror option:selected').val() + '&leadfrom=' + $('select#from option:selected').val();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.summary').fadeOut('slow');
//show the success message
$('.success').fadeIn('slow');
$('#submit_fourth').attr("disabled", true);
window.location = "http://www.stackoverflow.com";
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, there has been a problem with this form. Thank you');
}
});
//cancel the submit button default behaviours
return false;
});
//back button
$('.back').click(function(){
var container = $(this).parent('div'),
previous = container.prev();
switch(previous.attr('id')) {
case 'first_step' : $('#progress_text').html('0% Complete');
$('#progress').css('width','0px');
break;
case 'second_step': $('#progress_text').html('33% Complete');
$('#progress').css('width','113px');
break;
case 'third_step' : $('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
break;
default: break;
}
$(container).slideUp();
$(previous).slideDown();
});
});
and the HTML...
<div class="outer-formbody">
<div class="formbody">
Close
<div id="container">
<form action="#" method="post">
<!-- #second_step -->
<div id="second_step">
<h3>Book your appointment</h3>
<div class="form">
<input type="text" name="firstname" id="firstname" value="first name" />
<label for="firstname">Your First Name.<span>*</span></label><!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input type="text" name="lastname" id="lastname" value="last name" />
<label for="lastname">Your Last Name.<span>*</span></label><!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input type="text" name="email" id="email" value="email address" />
<label for="email">Your email address (not shared).<span>*</span></label> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input type="text" name="phone" id="phone" value="phone number" />
<label for="email">Your contact number (not shared).<span>*</span></label>
</div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input class="submit" type="submit" name="submit_second" id="submit_second" value="" />
</div>
<!-- #third_step -->
<div id="third_step">
<h3>Book your appointment</h3>
<div class="form">
<select id="service" name="service" class="required">
<option value="">Please Select</option>
<option>Power of Attorney</option>
<option>Property Trust</option>
<option>Disabled Trust</option>
<option>Discretionary Trust</option>
<option>Other Trust</option>
<option>Protection / Insurance</option>
<option>Other Service</option>
</select>
<label for="service">Select the service you require.<span>*</span></label> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<select id="location" name="location" class="required">
<option value="">Please Select</option>
<option>Staffordshire</option>
<option>Shropshire</option>
<option>West Midlands</option>
<option>Shropshire</option>
<option>Leicestershire</option>
<option>Birmingham</option>
<option>Cheshire</option>
<option>Other</option>
</select>
<label for="location">Select your home county.<span>*</span></label> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<select id="mirror" name="mirror" class="required">
<option value="">Please Select</option>
<option>Single</option>
<option>Couple</option>
</select>
<label for="country">Single or two documents (for a couple).<span>*</span></label> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<select id="from" name="from" class="required">
<option value="">Please Select</option>
<option>NHS/School/Council</option>
<option>Friend/Family Member</option>
<option>Other Public Sector Employer</option>
<option>Private Sector Employer</option>
<option>Internet Advert</option>
<option>Google</option>
<option>Newspaper</option>
<option>NetMums</option>
<option>MumsNet</option>
<option>Other</option>
</select>
<label for="from">Where did you hear about us?<span>*</span></label>
</div><!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input class="back" type="button" value="" />
<input class="submit" type="submit" name="submit_third" id="submit_third" value="" />
</div>
<!-- #fourth_step -->
<div id="fourth_step">
<h3>Book your appointment</h3>
<div class="form">
<div class="success">
</br>
</br>
</br>
</br>
</br>
<h3>Booking Submitted. <span>Please Wait . . .</span></h3>
</div>
<div class="summary">
<h3>Summary</h3>
<table class="table">
<tr><td>Name</td><td></td></tr>
<tr><td>Email</td><td></td></tr>
<tr><td>Phone</td><td></td></tr>
<tr><td>Service</td><td></td></tr>
<tr><td>Location</td><td></td></tr>
<tr><td>Single/Couple</td><td></td></tr>
<tr><td>From</td><td></td></tr>
</table>
</div>
</div> <!-- clearfix --><div class="clear"></div><!-- /clearfix -->
<input class="back" type="button" value="" />
<input class="send submit" type="submit" name="submit_fourth" id="submit_fourth"value="" />
</div>
</form>
</div>
<div id="progress_bar">
<div id="progress"></div>
<div id="progress_text">0% Complete</div>
</div>
<div></div>
</div></div>
</div>
and the PHP script to process the form....
<?php
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$firstname = ($_GET['firstname']) ? $_GET['firstname'] : $_POST['firstname'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$lastname = ($_GET['lastname']) ?$_GET['lastname'] : $_POST['lastname'];
$phone = ($_GET['phone']) ?$_GET['phone'] : $_POST['phone'];
$service = ($_GET['service']) ?$_GET['service'] : $_POST['service'];
$location = ($_GET['location']) ?$_GET['location'] : $_POST['location'];
$mirror = ($_GET['mirror']) ?$_GET['mirror'] : $_POST['mirror'];
$leadfrom = ($_GET['leadfrom']) ?$_GET['leadfrom'] : $_POST['leadfrom'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//if the errors array is empty, send the mail
if (!$errors) {
//recipient
$to = 'Alex <clansey2004#yahoo.co.uk>';
//sender
$from = $firstname . ' <' . $email . '>';
//subject and the html message
$subject = 'Lead from ' . $firstname;
$message = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
</Br>
<table>
<tr><td>First Name</td><td>' . $firstname . '</td></tr>
<tr><td>Lastname</td><td>' . $lastname . '</td></tr>
<tr><td>Location</td><td>' . $location . '</td></tr>
<tr><td>Email</td><td>' . $email . '</td></tr>
<tr><td>Phone</td><td>' . $phone . '</td></tr>
<tr><td>Service</td><td>' . $service . '</td></tr>
<tr><td>Mirror</td><td>' . $mirror . '</td></tr>
<tr><td>Lead From</td><td>' . $leadfrom . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $message, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
echo 'Back';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $message, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$message,$headers);
if ($result) return 1;
else return 0;
}
?>
I am sure I have made a silly mistake - any help would be greatly appreciated!!
Thanks
My guess is you need to urlescape the values with encodeURIComponent(), especially those with a slash inside.
I have an HTML form that posts to a php script that then emails me the forms contents.
I'm also using javascript form validation and some jquery ajax so that the page doesn't reload.
HTML -
<form action="mail.php" class="contactus" onsubmit="return ValidateRequiredFields();" name="contactus" method="POST">
<p class="floatleft" style="width:200px; background-color:#FF0000; line-height:50px; margin:0; padding:0;">Nameeeeee</p> <input class="sizetext" type="text" maxlength="10" name="name">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Email</p> <input class="sizetext" type="text" maxlength="10" name="email">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Telephone</p> <input class="sizetext" type="text" maxlength="10" name="telephone">
<p>Priority</p>
<select name="priority" size="1">
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="High">High</option>
<option value="Emergency">Emergency</option>
</select>
</select>
<p>Message</p><textarea name="message" rows="6" cols="25"></textarea><br />
<br />
<input class="buttonstyle" type="submit" value="Send">
</form>
<div id="formResponse">
</div>
PHP -
<?php $name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemailaddress";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>
Form validation and ajax -
<script type="text/javascript" language="JavaScript">
var FormName = "contactus";
var RequiredFields = "name,email,priority,message";
function ValidateRequiredFields()
{
var FieldList = RequiredFields.split(",")
var BadList = new Array();
for(var i = 0; i < FieldList.length; i++) {
var s = eval('document.' + FormName + '.' + FieldList[i] + '.value');
s = StripSpacesFromEnds(s);
if(s.length < 1) { BadList.push(FieldList[i]); }
}
if(BadList.length < 1) { return true; }
var ess = new String();
if(BadList.length > 1) { ess = 's'; }
var message = new String('\n\nThe following field' + ess + ' are required:\n');
for(var i = 0; i < BadList.length; i++) { message += '\n' + BadList[i]; }
alert(message);
return false;
}
function StripSpacesFromEnds(s)
{
while((s.indexOf(' ',0) == 0) && (s.length> 1)) {
s = s.substring(1,s.length);
}
while((s.lastIndexOf(' ') == (s.length - 1)) && (s.length> 1)) {
s = s.substring(0,(s.length - 1));
}
if((s.indexOf(' ',0) == 0) && (s.length == 1)) { s = ''; }
return s;
}
// -->
</script>
<script type="text/javascript">
$(document).ready(function() {
$(".contactus").submit(function() {
$.post("mail.php", $(".contactus").serialize(),
function(data) {
$("#formResponse").html(data);
}
);
return false;
});
});
</script>
What I'd like to know is how to hide the form after it's submitted.
$(".contactus").on('submit', function() {
$this = $(this);
$.post("mail.php", $(".contactus").serialize(), function(data) {
$("#formResponse").html(data);
$this.hide()
});
return false;
});
Or you could try:
$(document).ready(function() {
$(".contactus").on('submit', function(e) {
e.preventDefault();
$this = $(this);
$.ajax({
type: 'POST',
url: "mail.php",
data: $(".contactus").serialize()
}).done(function() { //done will only hide if the submit is successful, using always instead will alway hide the form
$this.hide();
});
});
});
Try
$('form.contactus').submit(function() {
$(this).hide();
});