FormData() coudn't extract form parameters from HTML - javascript

I have written a jQuery function whose purpose is to extract parameters from a form upon submitting it. To extract form data, I am using the function FormData() function. After that, I have also written a loop to print the form entries, but nothing is getting printed in the console.
My HTML form:
<div class="form-contact">
<form name="sentMessage" id="contactForm" class="contact-form" method="post" novalidate>
<div class="row">
<div class="col-md-6">
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Name<span>*</span></label>
<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Email Address<span>*</span></label>
<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block"></p>
</div>
</div>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Subject</label>
<input type="tel" class="form-control" placeholder="Subject" id="subject">
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Message<span>*</span></label>
<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block"></p>
</div>
</div>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12 text-right">
<button type="submit" name="button" class="btn btn-primary btn-lg">Send Message</button>
</div>
</div>
</form>
</div>enter code here
My JS file:
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
/*var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();*/
var firstName = name; // For Success/Failure Message*/
// Check for white space in name for Success/Fail message
var dat=new FormData($('#contactForm')[0]);
if(firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
for (var pair of dat.entries())
{
console.log(pair[0]+ ', '+ pair[1]);
}
$.ajax({
type: "POST",
url: "/signup",
data: dat,
processData: false,
contentType: false,
/*{
name: name,
subject: subject,
email: email,
message: message
},*/
//cache: false,
success: function(result) {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function(error) {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
console.log(error);
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
// $("a[data-toggle=\"tab\"]").click(function(e) {
// e.preventDefault();
// $(this).tab("show");
// });
});

Use this to get all the form parameters on client side
Var dat = $(this).serializeArray();
//this contains object of form submitted
For(Var i=0;i
//serializeArray returns an array of parameters which are not disabled and have name attribute

Related

Javascript/jquery to validate the form in button click?

Hi i have a class using needs validate in form is there a way for me to validate this on button submit onclick ? or a better way to improve the coding for this ?
Where i can even call the invalid feedback ?
and also when button click it will check the valdiation first before call the database
As this code got some problem later in the end where i couldnt validate anything when button click as it passes to the database immediately without the validation check .
(function validateForm() {
'use strict';
var forms = document.getElementsByClassName('needs-validation');
Array.from(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.stopPropagation();
event.preventDefault();
}
form.classList.add('was-validated');
}, false)
})
})();
<form id="form" class="needs-validation" onsubmit="return validateForm()">
<!-- <label id="mandatoryField" class="hiddenfield" hidden>* is mandatory</label> -->
<div class="form-group row nameform">
<label for="validationName" class="col-form-label nameadduser">Name:</label>
<div class="col-6">
<input name="validationName" type="text" class="form-control" id="validationName" placeholder="Name" title="Name can be any. e.g. john" required>
<div class="invalid-feedback">
Enter a Name!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationEmail" class="col-form-label emailadduser">Email:</label>
<div class="col-6">
<input name="validationEmail" type="email" class="form-control emails" id="validationEmail" placeholder="example1#gmail.com" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
required>
<div style="margin-left: 3px;" class="invalid-feedback">
Enter a correct Email format!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationUserName" class="col-form-label usernameadduser">Username:</label>
<div class="col-6 ">
<input name="validationUserName" type="text" class="form-control " id="validationUserName" placeholder="Username" pattern="^(?=.{4,}$)(?:[a-zA-Z\d]+(?:[a-zA-Z\d])*)+$" title="Username should be at least 4 letter" required>
<div class="invalid-feedback">
Username must meet the following requirements:
<b>At least four letter</b>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label oldpasswordadduser">Old<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" type="password" class="form-control pass" id="oldpasswords" placeholder="Password" required>
<i class="bi bi-eye-slash" id="toggleoldPassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label passwordadduser">Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="passwords" placeholder="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{7,}$" title="Password should be like this. e.g. A123de!123"
required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
<div id="passwordvalidator" class="invalid-tooltip password-notmeet">
Password must meet the following requirements:
<br><br>
<label class="color-text"> At least one capital letter</label>
<br>
<label class="color-text"> At least one special character</label>
<br>
<label class="color-text"> At least one number</label>
<br>
<label class="color-text"> Be at least 7 letter</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationconfirmpassword" class="col-form-label passwordadduser">Re-enter<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationconfirmpassword" onChange="onChange()" type="password" class="form-control confirmpass" id="confirm_password" placeholder="Confirm Password" required>
<i class="bi bi-eye-slash" id="toggleconfirmPassword"></i>
<div style="margin-left: 20px;" class="invalid-tooltip">
Password do not match or value is null!
</div>
</div>
</div>
<div id="passwordconfirm"></div>
<div class="form-group row">
<label for="validationRole" class="col-form-label role">Role:</label>
<div class="col-3 ">
<select class="select-user-role custom-select-sm col-11" id="select-user-role" required>
<option class="selectrole" selected disabled value="">Select ....</option>
</select>
<div style="margin-left: 10px;" class="invalid-feedback">
Enter a valid user role!
</div>
</div>
</div>
<div class="form-group row placeholderimage">
<img src="" id="output" width="400" height="400" style="border-radius: 50%;" />
<input id="file-upload-input" type="file" accept="image/*" onchange="encodeImageFileAsURL(event);">
</div>
<button id="submitbtn" type="submit" class="btn-primary submitbutton" disabled>Done</button>
</form>
I have a button onclick where i got my database out when click which is this code it is with sweetalert as well not sure do we need to put the prevent button for validation here ?
$('#submitbtn').click(function() {
//get input value field
var name = $('#validationName').val();
var email = $('#validationEmail').val();
var username = $('#validationUserName').val();
var oldpassword = $('#oldpasswords').val();
var password = $('#passwords').val();
var picture = document.getElementById("output").src;
var role = $('#select-user-role').val();
//making ajax call after this retrieve
$.ajax({
url: "https://ecoexchange.dscloud.me:8090/api/postWithRawBody",
method: "POST",
contentType: "text/plain;charset=UTF-8",
headers: {
// Generally used for queries that we're planning to use
query: `UserUpdate(,'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','','${formatParamString(password)}','','${formatParamString(role)}')`,
// apikey like oXkPNt3p6cuDobzBVjpsPUyawSYDFqFHVWPkijXZZstjVPLLWo
"Content-Type": "text/plain",
apikey: sessionStorage.getItem("apikey")
},
dataType: "text",
// May be quite long
// Usually an array
// Only for specific conditions
data: `UserUpdate(${getQueryInfo()["id"]},'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','${formatParamString(oldpassword)}','${formatParamString(password)}','${formatParamString(picture)}','${formatParamString(role)}')`,
success: function(data, textStatus, xhr) {
// showing response from API
// showing response box that is added
//console.log(data)
$('#response').html("<div class='alert alert-success'>" + "<b>Success!</b> The information have been updated <b>successfully</b>" + "</div>")
Swal.fire({
icon: 'success',
title: 'Update Successfully!',
html: 'The information have been updated successfully!<br>By pressing <b>okay</b> this page will go to <b>view users</b> page',
showCancelButton: true,
cancelButtonText: "Cancel",
allowOutsideClick: false,
allowEscapeKey: false,
confirmButtonText: 'Okay',
cancelButtonColor: '#9b3be7', // purple
confirmButtonColor: '#79b446', // light green
heightAuto: false,
})
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
.then(function(inputvalue) {
if (inputvalue.isConfirmed) {
window.location.assign('viewUsers.html?id=' + getQueryInfo()['id'])
} else if (inputvalue.isCancel) {
Swal.fire('')
}
})
},
error: function(xhr, textStatus, err) {
if (xhr["status"] == 409) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> There is an <b>duplicate</b> on username!" + "</div>")
//then
// setTimeout(function(){ window.location.reload(); },5000); //reload a page after 5 seconds
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'There is an <label class="color-text"><b>duplicate</b></label> on username!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>username</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
if (xhr["status"] == 400) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> The <b>old password </b> is incorrect!" + "</div>")
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'The <label class="color-text"><b>old password</b></label> is incorrect!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>old password</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
// if (xhr["status"] == "(failed)") {
// $('#response').html("<div class='alert alert-danger'>"+"<b>Error!</b> There is an <b>duplicate</b> on username! where you cant add in image"+"</div>")
// }
}
});
})

My contact form does not work, submit button is not functioning

I am using a Bootstrap theme for my portfolio website. As far as I know, I changed all the parameters in the default php- and js-files in order for my contact form to work. I also made sure I have the correct settings in my server. However, when I press the submit button, it does not send anything. I'm also not receiving any sort of error message.
Any idea where I went wrong/how to fix this issue?
In Javascript:
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
},
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true);
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>')
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false);
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
The PHP-file associated with it(I marked out my email):
<?php
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$to = '*****#******.com';
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#********.com\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
And the HTML-snippet:
<!-- Contact -->
<section id="contact">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading text-uppercase">Feel free to contact me!</h2>
<h3 class="section-subheading text-muted">How can I help you?</h3>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<form id="contactForm" name="sentMessage" novalidate="novalidate">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" id="name" type="text" placeholder="Your Name *" required="required" data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input class="form-control" id="email" type="email" placeholder="Your Email *" required="required" data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
<div class="form-group">
<input class="form-control" id="phone" type="tel" placeholder="Your Phone *" required="required" data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" id="message" placeholder="Your Message *" required="required" data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="clearfix"></div>
<div class="col-lg-12 text-center">
<div id="success"></div>
<button id="sendMessageButton" class="btn btn-primary btn-xl text-uppercase" type="submit">Send Message</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>

Posting a form with google recaptcha via ajax

I have the following 'contact me' form (in a partial) in OctoberCMS
<form name="sentMessage" id="contactForm" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="g-recaptcha" id="gcaptcha" data-sitekey="sitekeydataCjaelksjEJlakch"></div>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
When the user clicks submit - it's handled via javascript (which is what helps with input validation). I'm using JQuery.
The JS looks like this:
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var gcaptcha = $("#gcaptcha").data('sitekey');
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message,
gcaptcha: gcaptcha
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
The contact_me.php form looks like this:
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$secret = "alkfejasupersecretkeyalkjeociyseh13987fa9s8df7";
$gcaptcha = $_POST['gcaptcha'];
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$gcaptcha."&remoteip=".$remoteip;
$result = json_decode($url, true);
var_dump($result);
/*
if ($result['success'] == 1) {
//do mail here
}
// Create the email and send the message
$to = 'myemail#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
*/
?>
As you can see - I'm trying to just see if I'm even getting to the contact_me.php form which it doesn't appear I am. Before I had commented it out - the mail never sent - which is why I started playing around trying to see if my data is even hitting the contact_me.php page. I see the success message when submitting - but the data never goes anywhere and no email is ever had.
I can see in Firebug that the data is posting to contact_me - but I can't tell much beyond that. The var_dump doesn't work and I'm in need of further assistance to either better troubleshoot this issue or figure out what isn't working.
After a lot of help from Xorifelse in the comments I realized that the code was probably fine (or at least suitable).
I ended up going a different direction. I updated the form a bit so it looks like this:
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2>Contact Me</h2>
<hr class="star-primary">
</div>
</div>
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<form name="sentMessage" id="contactForm" data-request="onSend" data-request-success="alert('We have received your email. Thank you!'); this.reset();" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input name="name" type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input name="email" type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input name="phone" type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea name="contact-msg" rows="5" class="form-control" placeholder="Message" id="contact-msg" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="g-recaptcha" id="sitekey" data-sitekey="gcaptchasitekey3897vadf834fadf"></div>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-success btn-lg">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
Note the 'onSend' data-request parameter.
In the default layout - I put this snippet of PHP to handle the actual processing (the onSend function):
function onSend()
{
if(empty(post('name')) ||
empty(post('email')) ||
empty(post('phone')) ||
empty(post('contact-msg')) ||
empty(post('g-recaptcha-response')) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "Please fill out all required fields.";
return false;
}
// Collect input
$name = post('name');
$email = post('email');
$phone = post('phone');
$body = post('contact-msg');
$response = post('g-recaptcha-response');
$remoteip = $_SERVER['REMOTE_ADDR'];
$secret = "32supersecretkeyackjaBcjeLCJelahd832CDo";
$url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$remoteip);
$response = json_decode($url, true);
// Form Validation
$validator = Validator::make(
[
'name' => $name,
'email' => $email,
'phone' => $phone,
'contact-msg' => $body,
],
[
'name' => 'required',
'email' => 'required|email',
'contact-msg' => 'required',
]
);
if ($validator->fails())
{
$messages = $validator->messages();
throw new ApplicationException($messages->first());
}
// Make sure the captcha is verified before sending
if (isset($response['success'])&&$response['success']=="true"){
$to = config('mail.from.address');
$params = compact('name','email','phone','body');
Mail::sendTo($to, 'freelance::mail.contact', $params);
return true;
}
else {
return false;
}
}
I was able to trim down the JS file to this:
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
So it provides active validation as the user is typing (which is great).
This method also required a little additional setup on the backend:
You need to create a new 'Mail Template' (code: freelance::mail.contact) in the Settings portion of the backend (and of course, make sure your mail settings are setup)
I would have liked to do a little more JS once the submission is successful - so maybe in the future I'll work that into it - but this is now working as intended.

Modal Hide Not Working

The modal form submits, returns formSuccess, sends the email, returns the signup alert, but the modal does not hide. Any suggestions?
The modal html:
<div class="modal fade" id="signupModal" tabindex="-1" role="dialog" aria-labelledby="signupModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Provide a few details and we'll be in touch...</h4>
</div>
<div class="modal-body">
<form id="contactForm" role="form">
<input type="hidden" id="theme" name="theme" value="flatly"/>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Your name" required>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your email address" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" class="form-control" rows="5" placeholder="Have a question or comment?" required></textarea>
</div>
</div>
<div class="modal-footer">
<button id="form-submit" type="submit" class="btn btn-success">Sign Up</button>
</div>
</form> <!-- add tag v_07 -->
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
The signup alerts html:
<div class="container form-message">
<div class="row">
<div id="signupSuccess" class="alert alert-success" style="display:none">
<p id="signupSuccessText">Thanks for signing up for preview access, we'll be in touch! In the meantime join us on Twitter, Facebook, and LinkedIn.</p>
</div>
<div id="signupError" class="alert alert-info" style="display:none">
<p id="signupErrorText">Well this is embarrassing. It looks like we're having trouble. While we fix this, we can be reached at info#timbercheck.net</p>
</div>
</div>
</div>
And here is the code from js file.
$("#contactForm").submit(function(event){
event.preventDefault();
submitForm();
});
function submitForm(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
}
}
});
};
function formSuccess(){
$("#signupSuccess").show();
$("#signupModal").modal('hide'); // add v_07
};
function formError(){
$("#signupError").show();
$("#signupModal").modal('hide'); // add v_07
};
You should add data-dismiss="modal" instead on your button because you are anyway going to show another modal.
EDIT : Change type from submit to button
<button id="form-submit" type="button" class="btn btn-success" data-dismiss="modal">Sign Up</button>
And try this,
$("#form-submit").click(function(event){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "php/process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
} else {
formError();
}
}
});
};
function formSuccess(){
$("#signupSuccess").show();
$("#signupModal").modal('hide'); // add v_07
};
function formError(){
$("#signupError").show();
$("#signupModal").modal('hide'); // add v_07
};
Instead of..
$('#myModal').modal('hide')
This worked...
$('#myModal').hide();
$('.modal-backdrop').hide();
Source: https://stackoverflow.com/a/29560331/7069248
Could be related to version of Bootstrap
This solution works for me:
setTimeout(function(){
$('#close-modal').click();
$('#close-modal').click();
},200);

Confirm message sticks to bottom of contact form after submiting

I need help in figuring out what's happening with my confirmation message when the form submits. I'm creating a contact form with Bootstrap using jQuery, AJAX and PHP (mail function) to validate it. I want the form to hide and then display the confirmation message but for some reason, when the form submits, the confirmation message shows at the bottom of the form briefly (for 2 seconds) before hiding and then displaying the confirmation message. I can't figure out why this is happening.
Here's my HTML code:
<div id="contact" class="container-fluid">
<div class="col-md-6 col-md-offset-3 col-lg-6 col-md-offset-3 container-backdrop ">
<form data-toggle="validator" role="form" action="php/contact.php" id="contactForm" method="post">
<div class="row">
<h1 class="form">Say Hello!</h1>
<br>
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="fullname" placeholder="Full Name" required type="text">
<div class="help-block with-errors"></div>
</div>
<div class="col-xs-6 col-md-6 form-group">
<input class="form-control" id="email" placeholder="Email" required type="email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<input class="form-control" id="subjectline" placeholder="Subject" required type="text">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12 form-group">
<div class="row">
<textarea class="form-control input-lg" id="message" name="Message" rows="6" placeholder="Message" required></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="btn-group-wrap">
<div class="btn-group">
<div class="col-md-4">
<button class="btn btn-success btn-lg" type="submit">Submit</button>
</div>
</div>
</div>
</form>
<div id="msgSubmit" class="h3 text-center hidden">Message sent! Thanks for stopping by!</div>
</div>
</div>
Here's the jQuery code:
$(document).ready(function() {
$("#contactForm").validator().on("submit", function(event) {
if (event.isDefaultPrevented()) {} else {
event.preventDefault();
$("#msgSubmit").removeClass("hidden");
submitForm();
}
});
});
function submitForm() {
var name = $("#fullname").val();
var email = $("#email").val();
var subjectline = $("#subjectline").val();
var message = $("#message").val();
// Initiate Variables With Form Content
$.ajax({
type: "POST",
url: "php/contact.php",
data: "fullname=" + fullname + "&email=" + email + "&message=" + message + "&subjectline" + subjectline,
success: function(text) {
$("#msgSubmit").removeClass("hidden");
1000;
$("#contactForm").hide();
}
});
}
You are displaying the confirmation message before making the ajax request, and hiding the form after receiving the response, which explains what you're describing.
You can fix it by displaying the confirmation message and hiding the form at the same time:
$(document).ready(function() {
$("#contactForm").validator().on("submit", function(event) {
if (event.isDefaultPrevented()) {
} else {
event.preventDefault();
// note here
submitForm();
}
});
});
function submitForm(){
var name = $("#fullname").val();
var email = $("#email").val();
var subjectline = $("#subjectline").val();
var message = $("#message").val();
// Initiate Variables With Form Content
$.ajax({
type: "POST",
url: "php/contact.php",
data: "fullname=" + fullname + "&email=" + email + "&message=" + message + "&subjectline" + subjectline,
success : function(text){
$("#msgSubmit" ).removeClass("hidden");
1000;
$("#contactForm").hide();
$("#msgSubmit").removeClass("hidden"); // and here
}
});
}

Categories