Submiting form using javascript - javascript

I have a login form that has a validator with javascript, I am using Google invisible Recaptcha either.
when I don't use Recaptcha the form is working completely correct but when I am using Recaptcha it calls a javascript function to submit the form and I cannot use validator inside that function.
I do not have much knowledge about javascript so any help would be appreciated.
HTML Code:
<form class="form-horizontal form-material validate-form" id="loginform" method="post" action="" role="form">
<h3 class="box-title m-b-20">Login</h3>
<div class="Input-Style">
<div class="wrap-input2 validate-input" data-validate="Email is uvalid">
<input class="input2" id="inputEmail" type="text" name="username" autofocus>
<span class="focus-input2" data-placeholder="your email"></span>
</div>
</div>
<div class="Input-Style">
<div class="wrap-input2 validate-input" data-validate="password is required">
<input class="input2" id="inputPassword" type="password" name="password">
<span class="focus-input2" data-placeholder="your password"></span>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button id="login" class="btn btn-info btn-lg btn-block text-uppercase waves-effect waves-light g-recaptcha"
data-sitekey="" data-callback="enableSubmit">Login
</button>
</div>
</div>
</form>
Javascript Code:
(function ($) {
"use strict";
/*==================================================================
[ Validate ]*/
var username = $('.validate-input input[name="username"]');
var password = $('.validate-input input[name="password"]');
$('.validate-form').on('submit',function(){
var check = true;
if($(username).val().trim().match(/^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) {
showValidate(username);
check=false;
}
if($(password).val().trim() == ''){
showValidate(password);
check=false;
}
return check;
});
$('.validate-form .input2').each(function(){
$(this).focus(function(){
hideValidate(this);
});
});
function showValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).addClass('alert-validate');
}
function hideValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).removeClass('alert-validate');
}
})(jQuery);

Modify the first lines of your JavaScript:
[...]
/*==================================================================
[ Validate ]*/
var username = $('.validate-input input[name="username"]');
var password = $('.validate-input input[name="password"]');
var verifyCallback = function(){
var check = true;
[...]
So, the validation function is not bound to the submit event (which is caught by Recaptcha) but to a variable.
Additionally, at these lines after the validateCallback function:
[...]
return check;
});
grecaptcha.render('html_element', {
'sitekey' : 'your_site_key',
'callback': verifyCallback
});
[...]
Now, first the captcha will be checked and afterwards your validation will be performed as a so called "callback" method.

You need to use grecaptcha.render callback. You also need to create separate functions which will validate your form like this:
function formValidator() {
// validation script will be here
}
and pass this function to grecaptcha.render method
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : formValidator,
'theme' : 'dark'
});

Related

Google invisible reCaptcha is only working in Incognito mode

I have a Google reCAPTCHA setup on my contact form in my website.
and i'm trying to test it in both localhost and server as well but recaptcha is only working in incognito mode .
without capturing reCAPTCHA mails are sending .
Here my problem is grecaptcha.execute(); is not executing, Please suggest solution for this.
$("#cont_msg").keypress(function (e) {
var key = e.which;
if (key == 13) {
// the enter key code
$("#contact_form_submit").click();
return false;
}
});
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).keypress(function () {
$(this).parent().removeClass("error");
});
function sendMail() {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
let data = {
username: co_name,
useremail: co_email,
userphone: co_phone,
usercompany: co_company,
usermessage: co_message,
};
$("#loading").show();
$("#contact_form_submit").hide();
$.ajax({
type: "POST",
url: "contact_ajaxmail.php",
data: data,
success: function (contact) {
//grecaptcha.execute();
$("#loading").hide();
$("#contact_form_submit").show();
var i = contact.split("#");
if (i[0] == "1") {
$("#cont_name").val("");
$("#cont_email").val("");
$("#cont_phone").val("");
$("#cont_company").val("");
$("#cont_msg").val("");
$("#contact_err").html(i[1]);
$(".app_form_wrapper .apps_input").addClass("success");
setTimeout(function () {
$(".app_form_wrapper .apps_input").removeClass("success");
$(".app_form_wrapper .apps_input").removeClass("error");
$("#cont_email").parent().removeClass("error");
}, 2500);
} else {
$("#cont_name").val(data.username);
$("#cont_email").val(data.useremail);
$("#cont_phone").val(data.userphone);
$("#cont_company").val(data.usercompany);
$("#cont_msg").val(data.usermessage);
$("#contact_err").html(i[1]);
$(
".app_form_wrapper .apps_input input, .app_form_wrapper .apps_input textarea"
).each(function () {
if (!$(this).val()) {
$(this).parent().addClass("error");
} else {
if (i[0] == 3) {
$("#cont_email").parent().addClass("error");
} else {
$(this).parent().addClass("error");
}
$(this).parent().removeClass("error");
}
});
}
},
});
}
**My form**
Here iam trying to send mails for entered email
<!DOCTYPE html>
<html lang="en">
<!-- BEGIN HEAD -->
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<form class="app_form_wrapper" role="form" >
<div class="col-lg-6 text-left">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_name"placeholder="Name">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_email" placeholder="Email">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="tel" class="form-control" id="cont_phone" placeholder="Phone Number" minlength="10" maxlength="15">
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<input type="text" class="form-control" id="cont_company" placeholder="Company">
</div>
</div>
<div class="form-group apps-pulldown-20">
<div class="apps_input">
<textarea rows="10" class="form-control" id="cont_msg" placeholder="Message"></textarea>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="g-recaptcha"
data-sitekey="Site_key"
data-callback="sendMail"
data-size="invisible">
</div>
<p>
This site is protected by reCAPTCHA and the Google
Privacy Policy and
Terms of Service apply.
</p>
<a class="btn btn-default btn-lg contact_btn" id="contact_form_submit">Send</a>
<a class="btn btn-default btn-lg contact_btn" id="loading" style="display: none;">Sending...</a>
<p class="input_error"id="contact_err" style="color:#FF6666;position:absolute;font-size:14px;font-weight: 500;letter-spacing: 0.5px;bottom: 10px;left: 0;right: 0;">
</p>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#contact_form_submit").on("click", function () {
var co_name = $("#cont_name").val();
var co_email = $("#cont_email").val();
var co_phone = $("#cont_phone").val();
var co_company = $("#cont_company").val();
var co_message = $("#cont_msg").val();
if (
co_name != "" &&
co_email != "" &&
co_phone != "" &&
co_company != "" &&
co_message != ""
) {
grecaptcha.execute();
} else {
$("#loading").hide();
$("#contact_form_submit").show();
$("#contact_err").html("Please fill all the fields !!!!");
}
});
})
</script>
</body>
</html>
Captcha needs two things to make it work properly
Client side code in Javascript, this you have done by looks of it properly.
Server side code, without implementing server side code the captcha is useless as bots will just post straight to your PHP form without having to enter a captcha! This is your missing piece based on your comments.
See
https://developers.google.com/recaptcha/intro
Notice it says you need to do 2 steps, 1 client side, 2 verify the response:
https://developers.google.com/recaptcha/docs/verify
Google returns loads results but this seems to be an up to date article
https://phppot.com/php/php-contact-form-with-google-recaptcha/
Google implementing google captcha php

how to add multi captcha in same page and check both checkbox its fill

I have two forms on a single page, one of them is a login form and the other is a register form (two tabs) and I want to check the the captchas, but when I click the check captcha from register form I can't login.
The login form:
HTML:
<div id="loginUserTab" class="tab-pane fade">
<form>
<div class="form-group login-width-100">
<label for="id_number" class="m-rtl-label"><span class="requiredMark">*</span>passport number:</label>
<input type="text" class="form-control" id="pNo" name="pNo" data-validetta="required,minLength[10],maxLength[10]" lang="fa" style="text-align: left;">
</div>
<div class="form-group login-width-100">
<label for="mNumber" class="m-rtl-label"><span class="requiredMark"></span> telephone :</label>
<input type="text" class="form-control" id="tNumber" name="tNumber" data-validetta="required,minLength[11],maxLength[11]" lang="fa" style="text-align: left;">
</div>
<div class="form-group" style="float:right;padding-right: 20px;">
<div class="g-recaptcha" data-sitekey="...."></div>
</div>
<div class="form-group login-width-100">
<button type="submit" class="btn btn-primary colorGreenBTN">login</button>
</div>
</form>
</div>
JS:
var v = grecaptcha.getResponse();
if (v.length == 0) {
alert("fill the form");
return;
} else if (!$("#Terms").prop("checked")) {
alert("check the rules");
}
Simplest Way to validate as much g-captcha validate
Hope you have included api.js before </head> tag as per below
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit"></script>
Your HTML Code looks like below
<div class="g-recaptcha-contact" data-sitekey="Your Site Key" id="RecaptchaField2"></div>
<input type="hidden" class="hiddenRecaptcha" name="ct_hiddenRecaptcha" id="ct_hiddenRecaptcha">
<div class="g-recaptcha-quote" data-sitekey="Your Site Key" id="RecaptchaField1"></div>
<input type="hidden" class="hiddenRecaptcha" name="qt_hiddenRecaptcha" id="qt_hiddenRecaptcha">
After you add this code in footer with tag
var CaptchaCallback = function() {
var widgetId1;
var widgetId2;
widgetId1 = grecaptcha.render('RecaptchaField1', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_quote});
widgetId2 = grecaptcha.render('RecaptchaField2', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_contact});
};
var correctCaptcha_quote = function(response) {
$("#qt_hiddenRecaptcha").val(response);
};
var correctCaptcha_contact = function(response) {
$("#ct_hiddenRecaptcha").val(response);
};
And Last easy step for developer add Jquery Validation as per below
$("#form_id").validate({
ignore: [],
rules: {
ct_hiddenRecaptcha: { required: true, },
qt_hiddenRecaptcha: { required: true, },
},
});
If you have same class for both the forms, you can use it to validate above.

submit a form and prevent from refreshing it

i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}

Automatic Login

I'm trying to automatically login a user. The JavaScript code below here actually does that but only when I remove the 'login/submit' div (), and then stops working when I include the 'div'. I can't remove this 'div' as that is my submit button. I don't know how to get around this problem, any help will be appreciated.
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
"submit is not a function" means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work. Any of the form element name and id should not be submit, otherwise form.submit will refer to that element rather than submit function.
When you name the button submit, you override the submit() function on the form.
So changing the div/submit like this will work for you
<div class="login"><input type="submit" value="LOGIN" name="btnSubmit" data-theme="e" id="btnSubmit"></div>
And if you don't want to change the button name then you might call the submit function natively aswell, which looks a bit dirty..
document.EventConfirmRedirection.prototype.submit.call(document.EventConfirmRedirection);
//or
document.EventConfirmRedirection.prototype.submit.call($('#myForm')[0]);

What's the quickest way to build sign ups, logins and passwords for real users?

I'd like to learn how to password protect my sites, with custom login credentials that I chose.
Using custom html, css, and javascript to create the interface gets me to a point like this -> http://codepen.io/lexeckhart/pen/RPLPwX
But everything on that page is accessible to everyone. I risk being an idiot in saying I remember using php and mysql or sql to do the next part. Maybe.
To add onto the title question I would like to know is where I start creating this database? Can I do it with ftp?
HTML
<div id="successful_login" class="fix-middle">
<div class="container text-center">
<h1>Welcome back to the internet!</h1>
<p>You've successfully managed to log into a nonexistant account in order to test a login dialog box.<br> If you like it, you are welcomed to use it wherever you want, no strings attached.<br><br>Rerun the whole thing.</p>
</div>
</div>
<div id="successful_registration" class="fix-middle">
<div class="container text-center">
<h1>Welcome to the internet!</h1>
<p>You've successfully managed to register for a nonexistant account in order to test a registration dialog box.<br> If you like it, you are welcomed to use it wherever you want, no strings attached.<br><br>Rerun the whole thing.</p>
</div>
</div>
<div id="dialog" class="dialog dialog-effect-in">
<div class="dialog-front">
<div class="dialog-content">
<form id="login_form" class="dialog-form" action="" method="POST">
<fieldset>
<legend>Log in</legend>
<div class="form-group">
<label for="user_username" class="control-label">Username:</label>
<input type="text" id="user_username" class="form-control" name="user_username" autofocus/>
</div>
<div class="form-group">
<label for="user_password" class="control-label">Password:</label>
<input type="password" id="user_password" class="form-control" name="user_password"/>
</div>
<div class="text-center pad-top-20">
<p>Have you forgotten your<br><strong>username</strong> or <strong>password</strong>?</p>
</div>
<div class="pad-top-20 pad-btm-20">
<input type="submit" class="btn btn-default btn-block btn-lg" value="Continue">
</div>
<div class="text-center">
<p>Do you wish to register<br> for <strong>a new account</strong>?</p>
</div>
</fieldset>
</form>
</div>
</div>
<div class="dialog-back">
<div class="dialog-content">
<form id="register_form" class="dialog-form" action="" method="POST">
<fieldset>
<legend>Register</legend>
<div class="form-group">
<label for="user_username" class="control-label">Username:</label>
<input type="text" id="user_username" class="form-control" name="user_username"/>
</div>
<div class="form-group">
<label for="user_password" class="control-label">Password:</label>
<input type="password" id="user_password" class="form-control" name="user_password"/>
</div>
<div class="form-group">
<label for="user_cnf_password" class="control-label">Confirm password:</label>
<input type="password" id="user_cnf_password" class="form-control" name="user_cnf_password"/>
</div>
<div class="form-group pad-top-20 form-group-checkbox">
<div class="checkbox">
<label>
<input type="checkbox" id="user_terms" name="user_terms">
I have read and I agree with the Terms and Conditions
</label>
</div>
</div>
<div class="pad-btm-20">
<input type="submit" class="btn btn-default btn-block btn-lg" value="Continue"/>
</div>
<div class="text-center">
<p>Return to <strong>log in page</strong>?</p>
</div>
</fieldset>
</form>
</div>
</div>
</div>
JAVASCRIPT
// The "getFormData()" function retrieves the names and values of each input field in the form;
function getFormData(form) {
var data = {};
$(form).find('input, select').each(function() {
if (this.tagName.toLowerCase() == 'input') {
if (this.type.toLowerCase() == 'checkbox') {
data[this.name] = this.checked;
} else if (this.type.toLowerCase() != 'submit') {
data[this.name] = this.value;
}
} else {
data[this.name] = this.value;
}
});
return data;
}
// The "addFormError()" function, when called, adds the "error" class to the form-group that wraps around the "formRow" attribute;
function addFormError(formRow, errorMsg) {
var errorMSG = '<span class="error-msg">' + errorMsg + '</span>';
$(formRow).parents('.form-group').addClass('has-error');
$(formRow).parents('.form-group').append(errorMSG);
$('#dialog').removeClass('dialog-effect-in');
$('#dialog').addClass('shakeit');
setTimeout(function() {
$('#dialog').removeClass('shakeit');
}, 300);
}
// FORM HANDLER:
// form_name - This attribute ties the form-handler function to the form you want to submit through ajax. Requires an ID (ex: #myfamousid)
// custom_validation -
function form_handler(form_name, custom_validation, success_message, error_message, success_function, error_function) {
$(form_name).find('input[type="submit"]').on('click', function(e) { // if submit button is clicked
window.onbeforeunload = null; // cancels the alert message for unsaved changes (if such function exists)
$(form_name).find('.form-group .error-msg').remove();
var submitButton = this;
submitButton.disabled = true; // Disables the submit buttton until the rows pass validation or we get a response from the server.
var form = $(form_name)[0];
// The custom validation function must return true or false.
if (custom_validation != null) {
if (!custom_validation(form, getFormData(form))) {
submitButton.disabled = false;
return false;
}
}
e.preventDefault(); //STOP default action
});
$(document).click(function(e) { // Whenever the user clicks inside the form, the error messages will be removed.
if ($(e.target).closest(form_name).length) {
$(form_name).find('.form-group').removeClass('has-error');
setTimeout(function() {
$(form_name).find('.form-group .error-msg').remove();
}, 300);
} else {
return
}
});
}
// LOGIN FORM: Validation function
function validate_login_form(form, data) {
if (data.user_username == "") {
// if username variable is empty
addFormError(form["user_username"], 'The username is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_password == "") {
// if password variable is empty
addFormError(form["user_password"], 'The password is invalid');
return false; // stop the script if validation is triggered
}
$('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');
$('#dialog').addClass('dialog-effect-out');
$('#successful_login').addClass('active');
//return true;
}
// REGISTRATION FORM: Validation function
function validate_registration_form(form, data) {
if (data.user_username == "") {
// if username variable is empty
addFormError(form["user_username"], 'The username is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_password == "") {
// if password variable is empty
addFormError(form["user_password"], 'The password is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_cnf_password == "" || data.user_password != data.user_cnf_password) {
// if password variable is empty
addFormError(form["user_cnf_password"], "The passwords don't match");
return false; // stop the script if validation is triggered
}
if (!data.user_terms) {
// if password variable is empty
addFormError(form["user_terms"], "You need to read and accept the Terms and Conditions before proceeding");
return false; // stop the script if validation is triggered
}
$('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');
$('#dialog').addClass('dialog-effect-out');
$('#successful_registration').addClass('active');
//return true;
}
form_handler("#login_form", validate_login_form, null, null, null, null, null, null);
form_handler("#register_form", validate_registration_form, null, null, null, null, null, null);
var dialogBox = $('#dialog');
dialogBox.on('click', 'a.user-actions', function() {
dialogBox.toggleClass('flip');
});
$('#successful_login,#successful_registration').on('click', 'a.dialog-reset', function() {
$('#successful_login,#successful_registration').removeClass('active');
dialogBox.removeClass('dialog-effect-out').addClass('dialog-effect-in');
document.getElementById('login_form').reset();
document.getElementById('register_form').reset();
});
Store the credentials in MySQL in a database table (hashed), access the database via php, redirect the user using either php or javascript.

Categories

Resources