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()
Related
On my order site, I have 2 options: pick up and delivery.
When choosing pick up, nothing happens, but when choosing delivery, the delivery address will appear for the user to fill in.
I want to use JS to notify you that you need to enter your shipping address only I you tick the delivery box.
Thank you.
/*Notify when information is invalid.*/
function validate() {
var pickup = document.getElementById("pickup").checked;
var delivery = document.getElementById("delivery").checked;
var deladd = document.getElementById("delivery_address").value;
var biladd = document.getElementById("billing_address").value;
if ((pickup == "") && (delivery == "")) {
errMsg += "Select an option. \\n";
}
if ((deladd == false) && (deladd == "")) {
errMsg += "Delivery address can not be empty.\\n";
if (errMsg != "") {
alert(errMsg);
result = false;
}
return result;
}
function init() {
var regForm = document.getElementById("form");
regForm.onsubmit = validate;
}
window.onload = init;
<div class="box">Select an option:
<input type="radio" id="pickup" name="option" value="pickup" class="radio" onclick="hideAddress()">
<label for="pickup" class="check">Pick Up</label>
<input type="radio" id="delivery" name="option" value="delivery" class="radio" onclick="showAddress()">
<label for="delivery" class="check">Delivery</label>
</div><br>
<div class="show" id="show">
<!--Delivery address.-->
<input type="text" placeholder="delivery address:" class="box" id="delivery_address" name="delivery_address">
<!--Check the same as the delivery address or not.-->
<label for="checkbox"> billing address same as delivery address</label>
<input type="checkbox" id="same_address" name="same_adsress_or_not" value="same_adress" onclick="autoFill()">
</div>
/*Notify when information is invalid.*/
function validate() {
var pickup = document.getElementById("pickup").checked;
var delivery = document.getElementById("delivery").checked;
var deladd = document.getElementById("delivery_address").value;
var biladd = document.getElementById("billing_address").value;
if ((pickup == "") && (delivery == "")) {
errMsg += "Select an option. \\n";
}
if ((deladd == false) && (deladd == "")) {
errMsg += "Delivery address can not be empty.\\n";
if (errMsg != "") {
alert(errMsg);
result = false;
}
return result;
}
}//closed here
function init() {
var regForm = document.getElementById("form");
regForm.onsubmit = validate;
}
window.onload = init;
<div class="box">Select an option:
<input type="radio" id="pickup" name="option" value="pickup" class="radio" onclick="hideAddress()">
<label for="pickup" class="check">Pick Up</label>
<input type="radio" id="delivery" name="option" value="delivery" class="radio" onclick="showAddress()">
<label for="delivery" class="check">Delivery</label>
</div><br>
<div class="show" id="show">
<!--Delivery address.-->
<input type="text" placeholder="delivery address:" class="box" id="delivery_address" name="delivery_address">
<!--Check same as delivery address or not.-->
<label for="checkbox"> billing address same as delivery address</label>
<input type="checkbox" id="same_address" name="same_adsress_or_not" value="same_adress" onclick="autoFill()">
</div>
In your code, you appear to have forgotten to close the function validate()'s
curly brackets (never closed the bracket "{").
Always remember to close your brackets.
Hope this helps :).
(still shows errors because incomplete code)
Good day everyone! My problem is why the firstName & lastName error message not showing. The username & password error message is working fine. Even if the password and confirm password error is working fine. The only problem is when my firstName and lastName is empty no error message show. I already download the jQuery and include it to my head tag. I double check the id names if same with my html. I think there are same. Can somebody help me regarding to my problem? I will show you my codes below!
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
if (error_firstname = false && error_lastname = false) {
return true;
} else {
return false;
}
});
});
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>
This line is wrong:
if (error_firstname = false && error_lastname = false)
It's doing assignment, not comparison. Change that if/else to:
return !error_firstnames && !error_lastnames;
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
return !error_firstnames && !error_lastnames;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>
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);
});
}
});
Anyone knows what is wrong here?
Keep getting 500 Internal Server Error. -
"NetworkError: 500 Internal Server Error - http:// sitename /validationengine.php"
Somehow I guess it's something wrong with the php-code. Everything with the validation works until it's time for the send.
HTML
<form id="competition_form" accept-charset="UTF-8" enctype="multipart/form-data" method="post" name="val_form" action="validationengine.php">
<fieldset>
<div id="page1_form" class="pages_form">
<p>Line1</p><br>
<input type="checkbox" name="quest" class="quest_group" value="1"><span class="nr_checkboxes">1. </span>
<label for="quest">labeltext 1</label><br>
<input type="checkbox" name="quest" class="quest_group" value="x"><span class="nr_checkboxes">X. </span>
<label for="quest">labeltext X</label><br>
<input type="checkbox" name="quest" class="quest_group" value="2"><span class="nr_checkboxes">2. </span>
<label for="quest">labeltext 2</label><br>
<p>Text</p>
<textarea name="motivering" rows="4" cols="66" maxlength="100"></textarea>
</div>
<div id="page2_form" class="pages_form">
<input type="checkbox" name="prize_check" value="win 1">
<label for="prize_check">Win 1</label><br>
<input type="checkbox" name="prize_check" value="win 2">
<label for="prize_check">Win 2</label><br>
<div class="full_input input_blocks">
<label for="namn">Namn:</label>
<input type="text" name="namn" maxlength="100" value="" />
<span id="namn_error" class="error">Du måste skriva in ditt namn.</span>
</div>
<div class="full_input input_blocks">
<label for="adress">Adress:</label>
<input type="text" name="adress" maxlength="100" value="" />
<span id="adress_error" class="error">Du måste skriva in din adress.</span>
</div>
<div class="half_input input_blocks">
<label for="postnr">Postnr:</label>
<input type="text" name="postnr" maxlength="50" value="" />
<span id="postnr_error" class="error">Du måste skriva in ditt postnummer.</span>
</div>
<div class="half_input input_blocks">
<label for="ort">Ort:</label>
<input type="text" name="ort" maxlength="50" value="" />
<span id="ort_error" class="error">Du måste skriva in din bostadsort.</span>
</div>
<div class="half_input input_blocks">
<label for="email">Mejl:</label>
<input type="text" name="email" maxlength="50" value="" />
<span id="email_error" class="error">Du måste skriva in din mejl-adress.</span>
</div>
<div class="half_input input_blocks">
<label for="mobil">Mobil:</label>
<input type="text" name="mobil" maxlength="50" value="" />
<span id="mobil_error" class="error">Du måste skriva in ditt telefonnummer</span>
</div>
<div id="rules_box">
<input type="checkbox" name="rules_check" value="Tävlingsvillkor godkända">
<label for="rules_check">Jag har läst och godkänner <b>tävlingsvillkoren</b></label><br>
<span id="rules_error" class="error">Du måste godkänna tävlingsvillkoren för att tävla.</span>
</div>
<input type="submit" name="submit" value="" class="submit-button" id="submit_btn" />
</div>
</fieldset>
</form>
JS
$(function() {
$('.error').hide();
$("input[name='email']").onchange=function(){$('.error').hide();};
$("input[name='email']").click(function() {
$('.error').hide();
});
$(".submit-button").click(function() {
var form = $('#competition_form');
var name = $("input[name='namn']").val();
var adress = $("input[name='adress']").val();
var postnr = $("input[name='postnr']").val();
var ort = $("input[name='ort']").val();
var email = $("input[name='email']").val();
var mobil = $("input[name='mobil']").val();
var rules = $("input[name='rules_check']").is(':checked');
$('.error').hide();
if (name == "") {
$("#namn_error").show();
return false;
}
if (adress == "") {
$("#adress_error").show();
return false;
}
if (postnr == "") {
$("#postnr_error").show();
return false;
}
if (ort == "") {
$("#ort_error").show();
return false;
}
if (email == "" || !isValidEmailAddress( email ) ) {
$("#email_error").show();
return false;
}
if (mobil == "") {
$("#mobil_error").show();
return false;
}
console.log(rules);
if (!rules) {
$("#rules_error").show();
return false;
}
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType:'html',
success: function(data) {
$('#thankyou_pop').fadeIn(500);
},
error: function(data) {
//AJAX request not completed
}
});
return false;
});
});
function isValidEmailAddress(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);
};
PHP
<?php
if( isset($_POST) ){
// validation
$validationOK=true;
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
$EmailTo = "example#example.com";
$Subject = "Nytt Tävlingsbidrag";
$quest = "";
if (isset($_POST['quest'])) {
$answer = Trim(stripslashes($_POST['quest']));
if($answer == 1) {
$quest = "Rätt svar";
} else {
$quest = "Fel svar";
}
}
if($quest == "") {
$quest = "Inget svar";
}
$motivering = Trim(stripslashes($_POST['motivering']));
if ($motivering == "") {
$motivering = "Ingen motivering";
}
$vinst = "";
if (isset($_POST['prize_check'])) {
$win_answer = Trim(stripslashes($_POST['prize_check']));
if ($win_answer == "") {
$vinst = "Ingen vinst vald"
} else {
$vinst = $win_answer;
}
}
$namn = Trim(stripslashes($_POST['namn']));
$adress = Trim(stripslashes($_POST['adress']));
$postnr = Trim(stripslashes($_POST['postnr']));
$ort = Trim(stripslashes($_POST['ort']));
$Email = Trim(stripslashes($_POST['email']));
$mobil = Trim(stripslashes($_POST['mobil']));
$villkor = Trim(stripslashes($_POST['rules_check']));
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
} else {
// prepare email body text
$headers = "Berocca Boost Tävlingsbidrag" . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$Body = "<h3>Nytt Tävlingsbidrag</h3>
<p><strong>Fråga: </strong> {$quest} </p>
<p><strong>Motivering: </strong> {$motivering} </p>
<p><strong>Föredragen vinst: </strong> {$vinst} </p>
<p><strong>Namn: </strong> {$namn} </p>
<p><strong>Adress: </strong> {$adress} </p>
<p><strong>Postnr: </strong> {$postnr} </p>
<p><strong>Ort: </strong> {$ort} </p>
<p><strong>E-mail: </strong> {$Email} </p>
<p><strong>Mobil: </strong> {$mobil} </p>
<p><strong>Villkor accepterade: </strong> {$villkor} </p>
<br>
<p>IP address: {$ipaddress} Date: {$date} Time: {$time}</p>";
// send email
mail($EmailTo, $Subject, $Body, $headers);
}
}
?>
$vinst = "";
if (isset($_POST['prize_check'])) {
$win_answer = Trim(stripslashes($_POST['prize_check']));
if ($win_answer == "") {
$vinst = "Ingen vinst vald" //<====== (Missing semi-colon ";")
} else {
$vinst = $win_answer;
}
}
You have made a typo error. Missed a semicolon.
if ($win_answer == "")
{
$vinst = "Ingen vinst vald"
^^^ // Missing semicolon
}
else
{
$vinst = $win_answer;
}
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;
}