Ajax : one ajax request for another forms - javascript

I have 3 contact form in one page (header, page, footer). How i can create one ajax request for all form ? I want when user click each one form send data fron only this form. Just now send from all forms. I used hasClass for determining from which class sending data, but i can't it
HTML:
<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>
<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>
Ajax:
jQuery('.submit, .hy-submit').on('click', function(e) {
e.preventDefault();
// All data from form
var str = $(this).closest('form').serialize();
// Get current page url
var page_url = window.location.toString();
// Vars
var name = jQuery('#name').val();
var hy_name = jQuery('#hy_name').val();
var email = jQuery('#email').val();
var hy_email = jQuery('#hy_email').val();
var msg = jQuery('#msg').val();
var hy_msg = jQuery('#hy_msg').val();
var subj = jQuery('#subj').val();
var obj=$(this);
if($(obj).hasClass('hy-submit')){
validatehyEmail(hy_email);
if (hy_msg == '' || hy_email == '' || validatehyEmail(jQuery('#hy_email').val()) == false) {
validatehyEmail(hy_email);
validateText(jQuery('#hy_msg'));
validateText(jQuery('#hy_name'));
return false;
}
console.log('submit');
} else if ($(obj).hasClass('submit')) {
validateEmail(email);
if (msg == '' || email == '' || validateEmail(jQuery('#email').val()) == false) {
validateEmail(email);
validateText(jQuery('#msg'));
validateText(jQuery('#name'));
return false;
}
console.log('submit');
}
// Get checkbox value
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: ajaxactionurl,
data: "action=send_email&" + str + "&myCheckboxes=" + choice + "&url=" + page_url,
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'];
$url = $_POST['url'];
$hy_name = $_POST['hy_name'];
$from = 'contact#test.com';
$to = 'test#test.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 .= (!empty($url)) ? '<p><strong>Url:</strong> : '.$url .'</p>' : '';
$message .= (!empty($hy_name)) ? '<p><strong>User Name</strong> : '.$hy_name .'</p>' : '';
$message .= (!empty($hy_email)) ? '<p><strong>User Email</strong> : '.$hy_email .'</p>' : '';
$message .= (!empty($hy_msg)) ? '<p><strong>User Message</strong> : '.$hy_msg .'</p>' : '';
$message .= '</body></html>';
echo mail($to, $subject, $message, $headers);
return $msg;
die();
}

Use form id attribute and use preventDefault method to prevent the forms from submitting.
$('#form-id').preventDefault();

Related

Html and php form not submitting issue

Hi guys I have been having trouble with one of the websites using HTML and PHP
The form doesn't seem to submit or send a message. Attached is the code please any help will be great. Also, the PHP and javascript have been attached for reference.
Also sometimes the page doesn't respond to the button.
If anyone can fix the code will be great.
CONTACT FORM
/*-----------------------------------------------------------------------------------*/
function checkmail(input) {
var pattern1 = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (pattern1.test(input)) {
return true;
} else {
return false;
}
}
function proceed() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var phone = document.getElementById("phone");
var movingfrom = document.getElementById("movingfrom");
var movingto = document.getElementById("movingto");
var date = document.getElementById("date");
var msg = document.getElementById("message");
var errors = "";
if (name.value == "") {
name.className = 'error';
return false;
} else if (email.value == "") {
email.className = 'error';
return false;
} else if (checkmail(email.value) == false) {
alert('Please provide a valid email address.');
return false;
} else if (phone.value == "") {
phone.className = 'error';
return false;
} else if (movingfrom.value == "") {
movingfrom.className = 'error';
return false;
} else if (movingto.value == "") {
movingto.className = 'error';
return false;
} else if (date.value == "") {
date.className = 'error';
return false;
} else if (msg.value == "") {
msg.className = 'error';
return false;
} else {
$.ajax({
type: "POST",
url: "php/submit.php",
data: $("#contact_form").serialize(),
success: function(msg) {
//alert(msg);
if (msg) {
$('#contact_form').fadeOut(1000);
$('#contact_message').fadeIn(1000);
document.getElementById("contact_message");
return true;
}
}
});
}
};
<div class="contact-form">
<!-- Form -->
<div class="margin-top-50">
<div class="contact-form">
<!-- Success Msg -->
<div id="contact_message" class="success-msg"> <i class="fa fa-paper-plane-o"></i>Thank You. Your Message has been Submitted</div>
<!-- FORM -->
<form id="contact_form" class="contact-form" method="post" action="php/submit.php" onsubmit="return ValidateForm()">
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="name" id="name" placeholder="Your Name">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="email" id="email" placeholder="E-Mail">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="phone" id="phone" placeholder="Phone Number">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="movingfrom" id="movingfrom" placeholder="Moving From">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="text" class="form-control" name="movingto" id="movingto" placeholder="Moving To">
</label>
</li>
<li class="col-sm-6">
<label>
<input type="date" class="form-control" name="date" id="date" placeholder="Date">
</label>
</li>
<li class="col-sm-12">
<label>
<select class="form-control" id="typeofmove" placeholder="Date Of Move" required>
<option>Move Type</option>
<option>Residential Move</option>
<option>Office Move</option>
<option>Inter-City Move</option>
<option>Piano Move</option>
<option>Spa-Pool Move</option>
<option>Pool Table Move</option>
<option>Loading & Unloading Only</option>
<option>Packing</option>
<option>Assembly</option>
<option>TradeMe Pickups</option>
<option>Commercial Delivery</option>
<option>Packaging Material</option>
</select>
</label>
</li>
<li class="col-sm-12">
<label>
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Your Message"></textarea>
</label>
</li>
<li class="col-sm-12">
<button type="submit" value="submit" class="btn" id="btn_submit" onClick="proceed();">Submit</button>
</li>
</ul>
</form>
</div>
</div>
</div>
</div>
<div class="col-md-4 col-sm-5 col-xs-12">
SUBMIT.PHP /*-----------------------------------------------------------------------------------*/
<?php
// specify your email here
$to = 'testmail#gmail.com';
// Assigning data from $_POST array to variables
if (isset($_POST['name'])) { $name = $_POST['name']; }
if (isset($_POST['phone'])) { $name = $_POST['phone']; }
if (isset($_POST['email'])) { $from = $_POST['email']; }
if (isset($_POST['movingfrom'])) { $name = $_POST['movingfrom']; }
if (isset($_POST['movingto'])) { $name = $_POST['movingto']; }
if (isset($_POST['date'])) { $name = $_POST['date']; }
if (isset($_POST['typeofmove'])) { $name = $_POST['typeofmove']; }
if (isset($_POST['message'])) { $message = $_POST['message']; }
// Construct subject of the email
$subject = 'Booking Enquiry ' . $name;
// Construct email body
$body_message .= 'Name: ' . $name . "\r\n";
$body_message .= 'Email: ' . $from . "\r\n";
$body_message .= 'Phone: ' . $phone . "\r\n";
$body_message .= 'Moving From: ' . $movingfrom . "\r\n";
$body_message .= 'Moving To: ' . $movingto . "\r\n";
$body_message .= 'Date Of Move: ' . $date . "\r\n";
$body_message .= 'Message: ' . $message . "\r\n";
// Construct headers of the message
$headers = 'From: ' . $from . "\r\n";
$headers .= 'Reply-To: ' . $from . "\r\n";
$mail_sent = mail($to, $subject, $body_message, $headers);
if ($mail_sent == true){ ?>
<script language="javascript" type="text/javascript">
window.alert("Sent Successfuly.");
</script>
<?php } else { ?>
<script language="javascript" type="text/javascript">
window.alert("Error! Please Try Again Later.");
</script>
<?php
} // End else
?>
First of all you can try check your url.Is it correct or no.For example send anything via ajax and show the response at console log.If it is not working thats mean your url is wrong.

Send Form data in Email using PHP without refreshing the page

I have a contact section in my website. I want when a user submit the form all the data should be sent in email plus the page don't reload.
My form:
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" id="name" >
</div>
<div class="form-group">
<label for="email">E-Mail:</label>
<input type="email" class="form-control" name="email" id="email" >
</div>
<div class="form-group">
<label for="mobile">Mobile Number:</label>
<input type="text" class="form-control" name="mobile" id="mobile">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" rows="5" name="message" id="message"></textarea>
</div>
<button type="submit" id="send" class="btn btn-primary" style="width: 100%" name="form_submit">Send Message</button>
Javascript
$(document).ready(function(){
$('#send').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var message = $('#message').val();
var varData = 'name=' + name + '&email=' + email + '&mobile=' + mobile + '&message=' + message;
$.ajax({
type: 'POST',
url: 'process.php',
data: varData,
success: function() {
alert("message sent");
}
});
});
});
</script>
Process.php
if (isset( $_POST['form_submit'] ) ) {
// Do processing here.
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$message = $_POST['message'];
if ($name == '' || $email == '' || $mobile=='' || $message=='')
{
echo "<script> alert('please fill the field');
</script>";
exit;
}
elseif ($_POST["email"]<>'') {
$ToEmail = 'email#gmail.com';
$EmailSubject = 'Website Contact form';
$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 = "Name: ".$_POST["name"]."<br><br>";
$MESSAGE_BODY .= "email: ".$_POST["email"]."<br>";
$MESSAGE_BODY .= "mobile: ".nl2br($_POST["mobile"])."<br>";
$MESSAGE_BODY .= "message: ".nl2br($_POST["message"])."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
echo "<script> alert('mail sent')
</script>";
exit;
} else{
echo "<script> alert ('there is some problem');</script>";
};
}
?>
The problem is the form is not using the code mentioned in "process.php"
How can I ensure the form data is sent in email? I have searched the previous answers but couldn't fix this.

Contactform with different subjects Automaticly

What I have to do is when you click on assortiment -> roses.
http://binnenkijkenbij.nl/happycolors/roses.html
You see a page with roses, when you click on a rose it pops up in a lightbox.
Underneath the photo you can contact the company.
I want to add a custom subject for eacht flower. So if I click on the first Rose and click on contact us. A contact form has to show up or I go to the contactpage where the subject automaticly is filled with the name of the flower.
Does anyone know how I can fix this? I know some little php/javascript but, at this point I'm stuck.. I have on simple contactform where you can add an subject by yourself.
The HTML:
<div class="divide50"></div>
<div class="row">
<div class="col-sm-8">
<h1 class="post-title">Feel free to contact us</h1>
<p></p>
<div class="divide20"></div>
<div class="form-container">
<div class="response alert alert-success"></div>
<form class="forms" action="contact/form-handler.php" method="post">
<fieldset>
<ol>
<li class="form-row text-input-row name-field">
<input type="text" name="name" class="text-input defaultText required" title="Name (Required)"/>
</li>
<li class="form-row text-input-row email-field">
<input type="text" name="email" class="text-input defaultText required email" title="Email (Required)"/>
</li>
<li class="form-row text-input-row subject-field">
<input type="text" name="subject" class="text-input defaultText" title="Subject"/>
</li>
<li class="form-row text-area-row">
<textarea name="message" class="text-area required"></textarea>
</li>
<li class="form-row hidden-row">
<input type="hidden" name="hidden" value="" />
</li>
<li class="nocomment">
<label for="nocomment">Leave This Field Empty</label>
<input id="nocomment" value="" name="nocomment" />
</li>
<li class="button-row">
<input type="submit" value="Submit" name="submit" class="btn btn-submit bm0" />
</li>
</ol>
<input type="hidden" name="v_error" id="v-error" value="Required" />
<input type="hidden" name="v_email" id="v-email" value="Enter a valid email" />
</fieldset>
</form>
</div>
<!-- /.form-container -->
</div>
The PHP:
<?php
include('SMTPClass.php');
$use_smtp = '0';
$emailto = 'myemail#domein.com';
// retrieve from parameters
$emailfrom = isset($_POST["email"]) ? $_POST["email"] : "";
$nocomment = isset($_POST["nocomment"]) ? $_POST["nocomment"] : "";
$subject = 'Contactformulier Happy Colors';
$message = '';
$response = '';
$response_fail = 'There was an error verifying your details.';
// Honeypot captcha
if($nocomment == '') {
$params = $_POST;
foreach ( $params as $key=>$value ){
if(!($key == 'ip' || $key == 'emailsubject' || $key == 'url' || $key == 'emailto' || $key == 'nocomment' || $key == 'v_error' || $key == 'v_email')){
$key = ucwords(str_replace("-", " ", $key));
if ( gettype( $value ) == "array" ){
$message .= "$key: \n";
foreach ( $value as $two_dim_value )
$message .= "...$two_dim_value<br>";
}else {
$message .= $value != '' ? "$key: $value\n" : '';
}
}
}
$response = sendEmail($subject, $message, $emailto, $emailfrom);
} else {
$response = $response_fail;
}
echo $response;
// Run server-side validation
function sendEmail($subject, $content, $emailto, $emailfrom) {
$from = $emailfrom;
$response_sent = 'Thank you. Your messsage has been received.';
$response_error = 'Error. Please try again.';
$subject = filter($subject);
$url = "Origin Page: ".$_SERVER['HTTP_REFERER'];
$ip = "IP Address: ".$_SERVER["REMOTE_ADDR"];
$message = $content."\n$ip\r\n$url";
// Validate return email & inform admin
$emailto = filter($emailto);
// Setup final message
$body = wordwrap($message);
if($use_smtp == '1'){
$SmtpServer = 'SMTP SERVER';
$SmtpPort = 'SMTP PORT';
$SmtpUser = 'SMTP USER';
$SmtpPass = 'SMTP PASSWORD';
$to = $emailto;
$SMTPMail = new SMTPClient ($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body);
$SMTPChat = $SMTPMail->SendMail();
$response = $SMTPChat ? $response_sent : $response_error;
} else {
// Create header
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\r\n";
// Send email
$mail_sent = #mail($emailto, $subject, $body, $headers);
$response = $mail_sent ? $response_sent : $response_error;
}
return $response;
}
// Remove any un-safe values to prevent email injection
function filter($value) {
$pattern = array("/\n/", "/\r/", "/content-type:/i", "/to:/i", "/from:/i", "/cc:/i");
$value = preg_replace($pattern, "", $value);
return $value;
}
exit;
?>

php simple contact form - stop submit on page refresh

The following PHP form works without any issues other than on refresh. If a user hits the refresh button after submitting the form, it re-submits the form.
Is there a way to use PHP or Jquery to stop the form re-submitting after refreshing the page?
I know in PHP there should be a way with Session, but I am not sure how.
contact.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.error_message{color:#cc0000;}
.form1{}
.form2{display:none;}
#succsess_page h1{background:url('http://example.com/ok.png')left no-repeat;padding-left:40px;color:#45a015; }
</style>
<h1>This is a simple contact form</h1>
<?php
//fields
$link_address = 'contact.php'; // page to redirect to
$honeypot = '';
$error = '';
$name = 'Name';
$email = 'Email';
$comments = 'Message';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['email_confirm'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
//error messages
if(trim($name) == 'Name') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($email) == 'Email') {
$error = '<div class="error_message">Need your Email</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Need your Email</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Need a valid email</div>';
} else if(trim($comments) == 'Message') {
$error = '<div class="error_message">A Message is required</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">A Message is required</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "email#example.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you. The following was sent to us. <br/><br/>$name<br/><br/>$email<br/><br/>$comments</p>";
echo "<a href='$link_address'>CLOSE THIS MESSAGE</a>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php echo $error; ?>
<!--form-->
<form method="post" action="" id="myform">
<p class="form1">Name: <input name="name" type="text" id="name" size="30" class="input1" value="<?php echo $name; ?>" onfocus="if(this.value == 'Name') { this.value = ''; }" onblur="toUpper(this.value); if(this.value == '') { this.value = 'Name'; }" value="Name" /></p>
<p class="form1">Email: <input name="email" type="text" id="email" size="30" class="input2" value="<?php echo $email; ?>" onfocus="if(this.value == 'Email') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Email'; }" value="Email" /></p>
<p class="form2">Confirm Email: <input name="email_confirm" type="text" id="email_confirm" size="30" value="<?php echo $email_confirm; ?>" /></p>
<p class="form1">Message: <textarea name="comments" cols="40" rows="3" id="comments" value="<?php echo $comments; ?>" onfocus="if(this.value == 'Message') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Message'; }" value="Message"><?php echo $comments; ?></textarea></p>
<p class="form1"><input name="contactus" type="submit" class="submit" id="contactus" value="Submit" /></p>
</form>
<!--end form-->
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>
<!------- capitalize first letter Name input ---->
<script>
function toUpper(mystring) {
var sp = mystring.split(' ');
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) {
f = sp[i].substring(0,1).toUpperCase();
r = sp[i].substring(1);
word[i] = f+r;
}
newstring = word.join(' ');
document.getElementById('name').value = newstring;
return true;
}
</script>
After the form has been submitted correctly run the following code:
header("Location :contact.php?msg=success");
This will redirect the user back to the contact form with an condition allowing for a message to be displayed.
if($_REQUEST['msg']){
echo "Contact Form Submitted Successfully!!";
}
If they hit refresh it will just bring up a successful message while displaying the contact form again.
Update:
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
header("Location: contact.php?msg=success");
}else{
header("Location: contact.php?msg=error");
}
Then for displaying:
<?php if($_REQUEST['msg']=="success"){
echo "Success Message Here.";
}elseif($_REQUEST['msg']=="error"){
echo "Error Message Here."
}
<!--form-->
<form method="post" action="" id="myform">

require fields based on dropdown selection

I'm stuck on the last part of something I want to achieve with a form I made.
When selecting a particular value from the dropdown list there will pop up 4 more name fields then the standard form. I don't know to require these optional fields. After filling the form the form will be send to an email address.
HTML:
<form id="register-form" method="post" class="form">
<div class="col-sm-12">
<select name="typeTicket" id="typeTicket" class="selectTicket">
<option value="EarlyBird">Early Bird</option>
<option value="Regular">Regular</option>
<option value="TeamTicket">Team Ticket</option>
</select>
</div>
<div class="col-sm-12">
<input name="name" id="name" type="text" placeholder="Voor- en achternaam" required>
</div>
<div class="col-sm-12">
<div id="extraNamen" style="display:none;">
<input type="text" id="name1" name="name1" placeholder="Voor- en achternaam">
<input type="text" id="name2" name="name2" placeholder="Voor- en achternaam">
<input type="text" id="name3" name="name3" placeholder="Voor- en achternaam">
<input type="text" id="name4" name="name4" placeholder="Voor- en achternaam">
</div>
</div>
<div class="col-sm-12">
<input name="email" id="email" type="email" placeholder="Email" required>
</div>
<div class="col-sm-12">
<input name="organisatie" id="organisatie" type="text" placeholder="Organisatie">
</div>
<div class="col-sm-12">
<input name="functie" id="functie" type="text" placeholder="Functie">
</div>
<div class="col-sm-12">
<input type="submit" value="Aanmelden" name="submit">
</div>
<p class="form-notification" style="display: none;">Bedankt voor de aanmelding, tot ziens op 18 juni 2015</p>
</form>
This script will collapse/expand the hidden form fields:
<script>
$('#typeTicket').on('change', function() {
if ($(this).val() === "TeamTicket") {
$("#extraNamen").show();
} else {
$("#extraNamen").hide();
}
});
</script>
Main JS function:
// Registration Form
RegisterForm: function () {
$("#register-form").submit(function (e) {
e.preventDefault();
var typeTicket = $("#typeTicket").val(),
name = $("#name").val(),
name1 = $("#name1").val(),
name2 = $("#name2").val(),
name3 = $("#name3").val(),
name4 = $("#name4").val(),
email = $("#email").val(),
organisatie = $("#organisatie").val(),
functie = $("#functie").val(),
dataString = '&typeTicket=' + typeTicket + '&name=' + name + '&name1=' + name1 + '&name2=' + name2 + '&name3=' + name3 + '&name4=' + name4 + '&email=' + email + '&organisatie=' + organisatie + '&functie=' + functie;
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) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "php/process.php",
data: dataString,
success: function () {
$('#register-form .form-notification').fadeIn(500);
}
});
} else {
if (!isValidEmail(email)) {
$('input#email').addClass('not-valid');
} else {
$('input#email').removeClass('not-valid');
}
if (name.length === 0) {
$('input#name').addClass('not-valid');
} else {
$('input#name').removeClass('not-valid');
}
}
return false;
});
},
PHP:
$youremail = "Email adress hidden";
// Register Form
if ( isset($_POST['email']) && isset($_POST['name']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// Detect & Prevent Header Injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
// Email Format
$body = "New User Registration \n\n";
$body .= "========== \n\n";
$body .= "Ticket type: $_POST[typeTicket] \n\n";
if($_POST[typeTicket] == "TeamTicket") {
$body .= "Naam: $_POST[name] \n\n";
$body .= "Naam: $_POST[name1] \n\n";
$body .= "Naam: $_POST[name2] \n\n";
$body .= "Naam: $_POST[name3] \n\n";
$body .= "Naam: $_POST[name4] \n\n";
} else {
$body .= "Naam: $_POST[name] \n\n";
}
$body .= "Organisatie: $_POST[organisatie] \n\n";
$body .= "Functie: $_POST[functie] \n\n";
$body .= "Email: $_POST[email] \n\n";
//Send email
mail( $youremail, "New User Registration", $body, "From:" . $_POST['email'] );
}
How about trying this...
<script>
$('#typeTicket').on('change', function() {
if ($(this).val() === "TeamTicket") {
$("#extraNamen").show();
$("#extraNamen").attr("required",true);
} else {
$("#extraNamen").hide();
}
});
</script>

Categories