Loading GIF after submitting form in jQuery in Laravel - javascript

I want to send an email after submitting a form in Laravel. For complete the send mail process Laravel needs sometimes(5-10 seconds). In that duration (5-10 seconds) I want to show a loader gif. While the mail is send the gif will disappear and a successful message will show.
Here is my form
<div class="book-appointment">
<img src="images/loader.gif" id="gif" style="display: block; margin: 0 auto; width: 100px; visibility: hidden;">
<h2>Make an appointment</h2>
<form action="#" method="post" style="margin-top: 3rem;">
<div class="left-agileits-w3layouts same">
<div class="gaps">
<p>Patient Name</p>
<input type="text" name="Patient Name" placeholder="" required=""/>
</div>
<div class="gaps">
<p>Phone Number</p>
<input type="text" name="Number" placeholder="" required=""/>
</div>
<div class="gaps">
<p>Email</p>
<input type="email" name="email" placeholder="" required="" />
</div>
<div class="gaps">
<p>Age</p>
<input type="text" name="age" placeholder="" required="" />
</div>
</div>
<div class="right-agileinfo same">
<div class="gaps">
<p>Select Date</p>
<input id="datepicker1" name="Text" type="text" value="" onfocus="this.value = '';" onblur="if (this.value == '') {
this.value = 'yy/mm/dd';}" required="">
</div>
<div class="gaps">
<p>Time</p>
<input type="text" id="timepicker" name="Time" class="timepicker form-control" value="">
</div>
<div class="gaps">
<p>Department</p>
<select class="form-control">
<option></option>
<option>Cardiology</option>
<option>Ophthalmology</option>
<option>Neurology</option>
<option>Psychology</option>
<option>Dermatology</option>
</select>
</div>
<div class="gaps">
<p>Gender</p>
<select class="form-control">
<option></option>
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<div class="clear"></div>
<input type="submit" value="Make an appointment">
</form>
</div>
My script
$('#add').click(function(event){
$('#gif').css('visibility', 'visible');
var patient_name = $('#patient_name').val();
var patient_number = $('#patient_number').val();
var patient_email = $('#patient_email').val();
var patient_age = $('#patient_age').val();
var patient_gender = $('#patient_gender').find(":selected").val();
var service_id = $('#service_id_search').find(":selected").val();
var schedule_time_id = $('#schedule_time_id').find(":selected").val();
var date = $('#datepicker1').val();
if(patient_name == '' || patient_number == '' || patient_email == '' || patient_age == '' || patient_gender == '' || service_id == '' || schedule_time_id == '' || date == '')
{
alert('Empty input field exist');
}
else if(isNaN(patient_number))
{
alert('Please insert numbers in Patient Number field');
}
else if(isNaN(patient_age))
{
alert('Please insert numbers in Age field');
}
else
{
$.get( 'confirm_appointment', {'patient_name': patient_name, 'patient_number': patient_number, 'patient_email': patient_email, 'patient_age': patient_age, 'patient_gender': patient_gender, 'service_id': service_id, 'schedule_time_id': schedule_time_id, 'date': date, '_token':$('input[name=_token]').val()}, function( data )
{
// console.log(data);
$('#exampleModal .bg-agile .book-appointment h2').remove();
$('#exampleModal .bg-agile .book-appointment form').remove();
trHTML = '';
if(data > 0)
{
trHTML += "<h2> Your appointment is successfully submitted </h2>";
}
else
{
trHTML += "<h2> No </h2>";
}
trHTML += "<center><a href='/'><button class='btn btn-secondary btn-lg' style='padding: 16px 20px 20px 20px; color: #fff; margin-top:20px;'>Go Back to Homepage</button></a></center>";
$('#exampleModal .bg-agile .book-appointment').append(trHTML);
// console.log(data);
// $("#report").load(location.href + " #report");
});
}
});
I have already see this article [Show loading gif after clicking form submit using jQuery but not working...
Anybody help please ?

Showing a div while sending an ajax request, You can use ajaxStop() and ajaxStart() together. here is an example.
var $loading = $('#yourloadingdiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
Hope this helps.

you could use in this way
//start actions
$('#your-loader').show();
$.post(endpoint, options, function(response){
$('#your-loader').hide();
}).fail(function(){
$('#your-loader').hide();
});

Add id both form and image.
Now inside javascript $('#add').click(function(event){}) function do the following
$('#appointment-form').hide();
$('#gif').show();
While successfully send the mail, just hide the gif id lnside the ajax
$('#gif').hide();
Here is my full code
$('#add').click(function(event){
$('#appointment-form').hide();
$('#gif').css('margin-top','80px');
$('#gif').show();
var patient_name = $('#patient_name').val();
var patient_number = $('#patient_number').val();
var patient_email = $('#patient_email').val();
var patient_age = $('#patient_age').val();
var patient_gender = $('#patient_gender').find(":selected").val();
var service_id = $('#service_id_search').find(":selected").val();
var schedule_time_id = $('#schedule_time_id').find(":selected").val();
var date = $('#datepicker1').val();
if(patient_name == '' || patient_number == '' || patient_email == '' || patient_age == '' || patient_gender == '' || service_id == '' || schedule_time_id == '' || date == '')
{
alert('Empty input field exist');
}
else if(isNaN(patient_number))
{
alert('Please insert numbers in Patient Number field');
}
else if(isNaN(patient_age))
{
alert('Please insert numbers in Age field');
}
else
{
$.get( 'confirm_appointment', {'patient_name': patient_name, 'patient_number': patient_number, 'patient_email': patient_email, 'patient_age': patient_age, 'patient_gender': patient_gender, 'service_id': service_id, 'schedule_time_id': schedule_time_id, 'date': date, '_token':$('input[name=_token]').val()}, function( data )
{
$('#exampleModal .bg-agile .book-appointment h2').remove();
$('#exampleModal .bg-agile .book-appointment form').remove();
trHTML = '';
if(data > 0)
{
trHTML += "<h2 style:'margin-top'> Your appointment is successfully submitted </h2>";
}
else
{
trHTML += "<h2> No </h2>";
}
trHTML += "<center><a href='/'><button class='btn btn-secondary btn-lg' style='padding: 16px 20px 20px 20px; color: #fff; margin-top:20px;'>Go Back to Homepage</button></a></center>";
$('#gif').hide();
$('#exampleModal .bg-agile .book-appointment').append(trHTML);
});
}
});

Related

form is getting submitted even after returing false

my script
<script>
function hii(Name,Mobile){
let Count=0;
if(Name=="" || Name==null){
document.getElementById('nameerror').style.display='block';
document.getElementById('nameerror').innerHTML='Please Enter Student Name';
Count++;
}
if(Mobile=="" || Mobile==null){
document.getElementById('mobileerror').style.display='block';
document.getElementById('mobileerror').innerHTML='Please Enter Student Mobile';
Count++;
}
if(Count>0){
alert(Count);
return false;
}
}
</script>
Html
<form action="addstudent.php" method="POST" onsubmit="hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
<input type="text" name='name' id="name" placeholder="Enter Student Name"><br><br>
<label for="" id="nameerror" style="display: none;color:red;font-size:small;"></label>
<input type="number" name='mobile' id='mobile' placeholder="Enter Mobile Number"><br><br>
<label for="" id="mobileerror" style="display: none;color:red;font-size:small;"></label>
<input type="submit" value="add">
</form>
im getting count as 2 via alert after submitting form with no data which means there are no errors in my html and javascript code and i cant find any flashing errors in console
What you need is to pass an event to the submit function, and use event.preventDefault() to stop the submission.
function hii(event, Name, Mobile) {
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
action="addstudent.php"
method="POST"
onsubmit="hii(
event,
document.getElementById('name').value,
document.getElementById('mobile').value
)"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
A better solution is to use addEventListener()
document.querySelector("#form1").addEventListener("submit", hii);
function hii(event) {
const Name = document.querySelector("#name").value;
const Mobile = document.querySelector("#mobile").value;
let Count = 0;
if (Name == "" || Name == null) {
document.getElementById("nameerror").style.display = "block";
document.getElementById("nameerror").innerHTML =
"Please Enter Student Name";
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById("mobileerror").style.display = "block";
document.getElementById("mobileerror").innerHTML =
"Please Enter Student Mobile";
Count++;
}
if (Count > 0) {
event.preventDefault();
alert(Count);
}
}
<form
id="form1"
action="addstudent.php"
method="POST"
>
<input
type="text"
name="name"
id="name"
placeholder="Enter Student Name"
/><br /><br />
<label
for=""
id="nameerror"
style="display: none; color: red; font-size: small"
></label>
<input
type="number"
name="mobile"
id="mobile"
placeholder="Enter Mobile Number"
/><br /><br />
<label
for=""
id="mobileerror"
style="display: none; color: red; font-size: small"
></label>
<input type="submit" value="add" />
</form>
You have to return the value in the handler
<form action="addstudent.php" method="POST" onsubmit="return hii(
document.getElementById('name').value,
document.getElementById('mobile').value
)">
But better yet is to keep it all together in your script
<form action="addstudent.php" method="POST">
<!-- remove the onsubmit here -->
<input type="submit" value="add">
<!-- we'll put the listener here -->
Then, your script
document.querySelector('input[type="submit"]').addEventListener('click', function(e) {
e.preventDefault();
let Count = 0;
let Name = document.getElementById('name').value;
let Mobile = document.getElementById('mobile').value
if (Name == "" || Name == null) {
document.getElementById('nameerror').style.display = 'block';
document.getElementById('nameerror').innerHTML = 'Please Enter Student Name';
Count++;
}
if (Mobile == "" || Mobile == null) {
document.getElementById('mobileerror').style.display = 'block';
document.getElementById('mobileerror').innerHTML = 'Please Enter Student Mobile';
Count++;
}
if (Count > 0) {
alert(Count);
return false;
}
document.querySelector('form').submit()
})

How to select a radio button in PHP

I have my PHP file included in my views for AJAX.
So my problem is that when I try to select the radio inputs with their values I instead get my else statement. I also have my additional CSS and Javascript, but I don't think they are causing the value. It looks like radio buttons may not be made for PHP so if I may not find a solution then maybe I should try to convert them into a checkbox.
Edit: I have managed to get the result of the post and it's returning: [object OBJECT]
Is there a way to get the value of my checked radios for the player account?
Radio's PHP
$usernameError = "";
$passwordError = "";
$termsandconditionsError = "";
$playAccount = "";
$creatorAccount = "";
$account = "";
$error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameError = "Username is required.";
echo $usernameError;
} else {
$username = signupform_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordError = " Password is required.";
echo $passwordError;
} else {
$password = signupform_input($_POST["password"]);
}
if(!empty($_POST['account'])) {
$playAccount = $_POST['account'];
}
if(!empty($_POST['creatorAccount'])) {
$creatorAccount = $_POST['creatorAccount'];
}
if(isset($_POST['account'])) {
if(!empty($_POST['account'] || $_POST['creatorAccount'])) {
$account = $_POST['account'].', '.$_POST['creatorAccount'];
}
}
if(isset($_POST['loginActive'])) {
if($_POST['loginActive'] == "0" && $usernameError == "" && $passwordError == "" && $termsandconditionsError == "") {
$query = "SELECT * FROM users WHERE username = '". mysqli_real_escape_string($link, $_POST['username'])."' LIMIT 1";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) > 0) {
$error = "That username is already taken.";
echo $error;
} else {
echo "<p style='color: green'>Hi</p>";
$query = "INSERT INTO `users` (`username`, `password`, `plan`) VALUES ('". mysqli_real_escape_string($link, $_POST['username'])."', '". mysqli_real_escape_string($link, $_POST['password'])."', '". mysqli_real_escape_string($link, $account)."')";
echo $query;
}
}
}
}
Form
<div class="container" style="margin: 50px;">
<form method="post" id="signupForm" class="signupForm">
<h2>Signup</h2>
<input type="hidden" name="loginActive" id="loginActive" value="0">
<br>
<div class="form-group row">
<label for="username" class="col-lg-16 col-form-label">Username:</label>
<div class="col-lg-8">
<input type="text" class="form-control signupInput" name="username" id="username" aria-describedby="username" autocomplete="username" autofocus required>
</div>
<p><span class="error"><?php echo $usernameError;?></span><p>
</div>
<div class="form-group row">
<label for="password" class="col-lg-16 col-form-label">Password:</label>
<div class="col-lg-8">
<input type="password" class="form-control signupInput" id="Password" name="password" autocomplete="current-password" required>
</div>
<p><span class="error"><?php echo $passwordError;?></span><p>
</div>
<h4>Account Type <i class="far fa-question-circle info" data-toggle="tooltip" data-placement="right" title="Whenever you have all free accounts checked, payment method should be hidden, but if not then click on any paid account and then click back!" height="16px"></i></h4>
<p>Visit Plan for pricing details.</p>
<input type="radio" id="freePlayerAccount" class="free playAccount" name="account" value="1" checked>
<label for="freePlayerAccount">Player: Free Account $0.00/Mo</label><br>
<input type="radio" id="proPlayerAccount" class="paid playAccount" name="account" value="2">
<label for="proPlayerAccount">Player: Pro Account $5.99/Mo</label><br>
<input type="radio" id="premiumPlayerAccount" class="paid playAccount" name="account" value="3">
<label for="premiumPlayerAccount">Player: Premium Account $9.99/Mo</label><br>
<hr>
<input type="radio" id="creatorFreeAccount" class="creatorAccount" name="creatorAccount" value="4" class="free">
<label for="creatorFreeAccount">Creator: Free Account $0.00/Mo</label><br>
<input type="radio" id="creatorProAccount" class="paid creatorAccount" name="creatorAccount" value="5">
<label for="creatorProAccount">Creator: Pro Account $9.99/Mo</label><br>
<input type="radio" id="creatorPremiumAccount" class="paid creatorAccount" name="creatorAccount" value="6">
<label for="creatorPremiumAccount">Creator: Premium Account $14.99/Mo</label><br>
<hr>
<div class="hiddenPaymentMethod"> <h5>Payment Method</h5>
<input type="radio" id="Paypal" name="payment" value="Paypal" class="payment">
<label for="Paypal">Paypal</label><br>
<input type="radio" id="creditCard" name="payment" value="CreditCard" class="payment">
<label for="creditCard">Credit Card</label><br>
<input type="text" style="display:none;" name="creditCardNumber" id="creditCardNumber" placeholder="Card Number">
<input type="radio" id="debitCard" name="payment" value="DebitCard" class="payment">
<label for="debitCard">Debit Card</label>
<input type="text" style="display:none;" name="debitCardNumber" id="debitCardNumber" placeholder="Card Number">
<br></div>
<br>
<input type="checkbox" id="termsAndConditions" class="conditions" name="termsandconditions" value="0">
<label for="termsAndConditions"> I have read and agreed to the Terms and Conditions <span data-toggle="modal" data-target="#exampleModal"><i class="far fa-question-circle questionMark"></i></span></label>
<p id="errors"></p>
<p id="tacError" style="color:red"></p>
<input type="button" class="btn btn-primary" name="signupButton" id="signUpButton" value="Submit">
</form>
</div>
Jquery
$("#signUpButton").click(function() {
$.ajax({
type: "POST",
url: "actionSignUp.php",
data: "username=" + $("#username").val() + "&password=" + $("#Password").val() + "&termsandconditions=" + $("#termsAndConditions").val() + "&account=" + $(".playAccount") + "&creatorAccount=" + $(".creatorAccount") + "&loginActive=" + $("#loginActive").val()
}).done(function(result) {
$("#errors").html(result);
}).fail(function(xhr, textStatus, errorThrown) {
alert("Error Requesting. Please Try Again Later.");
});
});
$('input:checkbox').change(
function(){
if ($(this).is(':checked')) {
$(this).val("1");
} else {
$(this).val("0");
}
});
$("#signUpButton").click(function(){
if($(".conditions").val() == "0") {
$("#tacError").html("Terms and Conditions are required");
} else {
$("#tacError").html("");
}
})
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '2') {
$(".hiddenPaymentMethod").show();
}
});
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '3') {
$(".hiddenPaymentMethod").show();
}
});
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '1') {
$(".hiddenPaymentMethod").hide();
$("#Paypal").removeAttr('checked');
}
});
$('input:radio[name="creatorAccount"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '6') {
$(".hiddenPaymentMethod").show();
$("#Paypal").attr('checked', 'checked');
}
});
$('input:radio[name="creatorAccount"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '5') {
$(".hiddenPaymentMethod").show();
$("#Paypal").attr('checked', 'checked');
}
});
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '2') {
$("#Paypal").attr('checked', 'checked');
}
});
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '3') {
$("#Paypal").attr('checked', 'checked');
}
});
$('input:radio[name="payment"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'CreditCard') {
$("#creditCardNumber").show();
}
});
$('input:radio[name="payment"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Paypal' || $(this).val() == 'DebitCard') {
$("#creditCardNumber").hide();
}
});
$('input:radio[name="payment"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'DebitCard') {
$("#debitCardNumber").show();
}
});
$('input:radio[name="payment"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Paypal' || $(this).val() == 'CreditCard') {
$("#debitCardNumber").hide();
}
});
$(function () {
$('[data-toggle="tooltip"]').tooltip();
})
In your AJAX call posting data is wrong way for params account and creatorAccount:
data: "username=" + $("#username").val() + "&password=" + $("#Password").val() + "&termsandconditions=" + $("#termsAndConditions").val() + "&account=" + $(".playAccount:checked").val() + "&creatorAccount=" + $(".creatorAccount:checked").val() + "&loginActive=" + $("#loginActive").val()
Instead of
data: "username=" + $("#username").val() + "&password=" + $("#Password").val() + "&termsandconditions=" + $("#termsAndConditions").val() + "&account=" + $(".playAccount") + "&creatorAccount=" + $(".creatorAccount") + "&loginActive=" + $("#loginActive").val()

Regular Expression always false

So I am writing some javascript to check if a user inputs a gmail address.
At the moment I have the code thats below, but no matter what I do it is giving me false. even when the input has #gmail.com...I feel that the mistake is how I am grabbing the user input in a variable and then testing it with test().
Javascript:
<script>
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {
}
}
</script>
html
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input
type="text"
class="form-control col-sm-1"
id="inputEmail"
placeholder="username#gmail.com"
/>
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>
You need to check the value of the input, var emailMatch = gmailPatt.test(email.value);
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email.value);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {}
}
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input type="text" class="form-control col-sm-1" id="inputEmail" placeholder="username#gmail.com" />
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>

Simple form skips validation/sending and goings straight to ajax message

I have been following this tutorial to validate a form on a HTML5 template I am working on modifying. Here is the link: http://englishpearls.net/dev/contact.html
As you see, the form goes straight to the ajax message and skips everything else. What am I doing wrong?
HTML
<div id="contact_form">
<form method="post" action="contact-post.html" >
<div class="to">
<input id="name" for="name" type="text" class="text" value="Name" name="userName" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">
<label class="error" for="name" id="name_error">This field is required.</label>
<input id="email" type="text" class="text" value="Email" name="userEmail" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}" style="margin-left: 10px">
<label for="email" class="error" for="email" id="email_error">This field is required.</label>
</div>
<div class="to">
<input id="phone" for="phone" type="text" class="text" value="Phone" name="userPhone" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Phone';}">
<label class="error" for="phone" id="phone_error">This field is required.</label>
<input id="subject" type="text" class="text" value="Subject" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Subject';}" style="margin-left: 10px">
<label class="error" for="subject" id="subject_error">This field is required.</label>
</div>
<div class="text">
<textarea id="message" value="Message:" name="userMsg" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message:</textarea>
<label class="error" for="message" id="message_error">This field is required.</label>
</div>
<div>
<input class="button" type="submit" value="Submit" name="submit" />
</div>
</div>
Jquery EDIT: Updated Script
<script type="text/javascript">
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
return false;
}
var subject = $("input#subject").val();
if (subject == "") {
$("label#subject_error").show();
$("input#subject").focus();
return false;
}
var message = $("input#message").val();
if (message == "") {
$("label#message_error").show();
$("input#message").focus();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "contact-post.html",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
});
}
});
return false;
});
});
</script>
Without the validation script, the email sends fine. Thanks!
The way your script is setup right now, the AJAX call will fire immediately, regardless of any input. It needs to be inside of this:
$(".button").click(function () {
}
function, which should have an if statement that will only allow the AJAX to fire if the validation of the form is successful.
Updated:
<div id="contact_form">
<form id="contact-post" method="post" action="contact-post.html" >
<div class="to">
<input id="name" for="name" type="text" class="text" placeholder="Name" name="userName" >
<label class="error" for="name" id="name_error">This field is required.</label>
<input id="email" type="text" class="text" placeholder="Email" name="userEmail" style="margin-left: 10px">
<label for="email" class="error" for="email" id="email_error">This field is required.</label>
</div>
<div class="to">
<input id="phone" for="phone" type="text" class="text" placeholder="Phone" name="userPhone" >
<label class="error" for="phone" id="phone_error">This field is required.</label>
<input id="subject" type="text" class="text" placeholder="Subject"style="margin-left: 10px">
<label class="error" for="subject" id="subject_error">This field is required.</label>
</div>
<div class="text">
<textarea id="message" placeholder="Message:" name="userMsg">Message:</textarea>
<label class="error" for="message" id="message_error">This field is required.</label>
</div>
<div>
<input class="button" type="submit" value="Submit" name="submit" />
</div>
JS:
<script type = "text/javascript">
$(function () {
$('.error').hide();
$("#contact-post").submit(function (event) {
alert("submitted");
event.preventDefault();
// validate and process form here
$('.error').hide();
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var subject = $("input#subject").val();
var message = $("#message").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
} else if (email == "") {
$("label#email_error").show();
$("input#email").focus();
} else if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
} else if (subject == "") {
$("label#subject_error").show();
$("input#subject").focus();
} else if (message == "") {
$("label#message_error").show();
$("input#message").focus();
} else {
var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "app/contact.php",
data: dataString,
success: function () {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$('#message').append("<img id='checkmark' src='web/images/check.jpg' />");
});
}
});
}
});
});
< /script>
That will work. Also I changed all of the value attributes in your HTML to placeholder attributes so they function as expected and don't get in the way of the validation.
Alternatively, since you're already using jQuery, you could check out jQuery Validate, a jQuery plugin that would make this much simpler
UPDATE:
I removed all of the onfocus/onblur attributes from your HTML and it works now. The JS in the onblur tags was filling the form with values, so it was able to pass validation. Look at this JSFIDDLE for a working verison
UPDATE 2:
The var message = $("input#message").val() should be var message = $("#message").val().
The first one is looking for an input with the id of "message", where as you have a textarea with that id. Changing this line will correct the blank message you're getting. (see the updated JS above)
Regarding this question,
I have noticed that in the first link I have the $(".button").submit(function (event) whereas in your config, in the same spot you have $("#contact-post").submit(function (event)
I have the validation being performed when a form with the id of "contact-post" gets submitted, instead of when the button gets submitted (which isn't possible). The reason the page with this JS/form is submitting is that the JS to validate never gets triggered.
It's possible (although unlikely) to submit the form without clicking that button, so we don't want the validation to be skipped on the off-chance that happens.
You could try adding "return true;" to the .click
$(".button").click(function () {
//...
//validation code
//...
//return true if passes validation
return true;
}
Have you thought about combining things like this:
$('yourForm').on('submit', function(event){
if ( formIsvalid() ) {
$.ajax({
...
});
} else {
// Do something else maybe?
}
event.preventDefault();
});
// Form validation.
function formIsvalid() {
... form validation here...
return true;
}

Reset My form after submission

After my form is submitted, I'd like to reset my form to display the original blank values. Here's the code:
PHP Form
<form action="index.php" method="post" id="contact_form" >
<div id="topic_error" class="error"><img src="images/error.png" /> What category should this be filed in?</div>
<div>
<select name="topic" id="topic">
<option value="">Please select a topic...</option>
<option value=" Computer Repair ">Computer Repair</option>
<option value=" Website Design ">Website Design</option>
<option value=" Say Hi ">Just Want to Say Hi</option>
</select>
</div>
<h4>NAME:</h4><div id="name_error" class="error"><img src="iamges/error.png" /> Please enter your name</div>
<div><input class="contact_name" type="text" name="name" id="name" placeholder="Enter Name" /></div>
<H4>EMAIL:</H4><div id="email_error" class="error"><img src="images/error.png" /> Please enter your email</div>
<div><input class="contact_email" type="text" name="email" id="email" placeholder="you#mail.com" /></div>
<h4>SUBJECT:</h4><div id="subject_error" class="error"><img src="images/error.png" /> Please enter a subject</div>
<div><input class="contact_subject" type="text" name="subject" id="subject" placeholder="How did you become so awesome?" /></div>
<h4>MESSAGE:</h4><div id="message_error" class="error"><img src="images/error.png" /> Please give us a few more details</div>
<div><textarea class="contact_message" name="message" id="message" placeholder="Give us some details"></textarea></div>
<div id="mail_success" class="success"><img src="images/success.png" /> Thank you. The mailman is on his way.</div>
<div id="mail_fail" class="error"><img src="images/error.png" /> Sorry, we don't know what happened. Please try again later.</div>
<div id="cf_submit_p">
<input class="submit" type="submit" id="send_message" value="">
</div>
</form>
The contact.js file
$(document).ready(function(){
$('#send_message').click(function(e){
e.preventDefault();
var error = false;
var topic = $('#topic').val();
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
if(topic.length == 0){
var error = true;
$('#topic_error').fadeIn(500);
} else {
$('#topic_error').fadeOut(500);
}
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
} else {
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
} else {
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#subject_error').fadeIn(500);
} else {
$('#subject_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
} else {
$('#message_error').fadeOut(500);
} if(error == false){
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
$.post("send_email.php", $("#contact_form").serialize(),function(result){
if(result == 'sent'){
$('#cf_submit_p').remove();
$('#mail_success').fadeIn(500);
} else {
$('#mail_fail').fadeIn(500);
$('#send_message').removeAttr('disabled').attr('value', 'Send Message');
}
});
}
});
});
I don't think the send_email.php file is needed, but I can put that up here if need be. I would assume (I know what happens when you assume) that this can be done with some sort of trigger in the javascript. I did try to add the line form.trigger('reset'); after the $('#mail_success').fadeIn(500); line but that did not work
It would be $("#contact_form").trigger("reset"), and $("#contact_form")[0].reset() should also work.
$('#contact_form').trigger('reset') should work.

Categories