Google invisible reCaptcha is only working in Incognito mode - javascript

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

Related

POST Ajax for multiple buttons in one form

I am creating one form that has Auth and Login buttons that is planned to handle sending out OTP and checking if OTP is valid respectively below.
I am following this Process a Form Submit with Multiple Submit Buttons in Javascript using below code, but when I get any button, javascript seems to be not working and I can't not get any console.log values. No error on the browser.
otplogin.html
<div id="otplogin">
<form class="form-horizontal" id="getotp" >
{% csrf_token %}
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value='auth' class="btn">Auth</button>
</div>
</div>
<div class="control-group">
<label class="control-label" for="otp">OTP</label>
<div class="controls">
<input type="otp" name="otp" id="otp" placeholder="OTP">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value='login' class="btn">Login</button>
</div>
</div>
</form>
</div>
<script type="text/javascript">
(function () { //the browser said the '$' as in the linked answer can not be recognized
$("#getotp btn").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "auth") {
console.log("CHECK 1");
$.ajax({
type:'POST',
url:'/getotp2',
data:{
username:$('#username').val()
,csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
console.log('POST1 success')
}
});
}
else if ($(this).attr("value") == "login") {
console.log("CHECK 2");
$.ajax({
type:'POST',
url:'/otplogin',
data:{
username:$('#username').val(),
otp:$('#otp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
console.log('POST2 success')
}
});
}
});
});
</script>
views.py
def otplogin(request):
if request.POST:
otpentered=request.POST.get('otp','')
if otpentered==otp:
return redirect('/main')
return render(request,'esearch/otplogin.html')
def getotp2(request):
logout(request)
username = otp = ''
if request.POST:
username = request.POST.get('username','')
otp = pyotp.TOTP('base32secret3232').now()
OTPEmail('You Auth',username,[],'Your auth is '+otp)
print ('POST'+username)
print ('POST'+otp)
return JsonResponse(json.dumps({'username':username,'otp':otp}),safe=False)
Appreciate any help on this
Your selection is wrong:
(function(){
$("#getotp btn").click(function (ev){...});}
Change to:
$(document).ready(function(){
$(".btn").click(function(ev){...});});
Or
$("#getotp .control-group .controls .btn").click(...

JS ajax event to by input change

I would like to have this code so I because if I go into the other input field, the other is updated
Or secound better input change
// on click search results...
$(document).on("touchend", "#ean", function() {
var value = $("#ean").val();
if (value.length != 0) {
//alert(99933);
searchData(value);
} else {
$('#search-result-container').hide();
}
});
// This function helps to send the request to retrieve data from mysql database...
function searchData(val) {
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="app/ajax-artstk/preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Please Wait...</span></div>');
$.post('app/ajax-artstk/controller.php', {
'ean': val
}, function(data) {
if (data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'><div class=\"alert alert-danger\" role=\"alert\">No Result Found...</div></div>");
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
});
}
<form action="#" method="POST" autocomplete="off">
<div class="form-group">
<input type="hidden" name="ausgang">
<div class="row">
<div class="col-md-2">
<label class="control-label"></label>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-2">
<label for="ean" class="control-label">EAN</label>
</div>
<div class="col-md-4">
<input type="text" name="ean" class="form-control" id="ean" value="" maxLength="100" autofocus>
<div id="search-result-container" style="border:solid 0px #BDC7D8;display:none; "></div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<label for="stueck" class="control-label">- Stück</label>
</div>
<div class="col-md-2">
<input type="text" name="stk" class="form-control" id="stk" value="" maxLength="3">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-success">Entnehmen</button>
<button type="reset" class="btn btn-danger">S</button>
<!-- PRINTBUTTON -->
</div>
</div>
</div>
<!-- END form-group -->
</form>
who can help me please who the very nice of you have already tried everything so far
I want to use that via Android and Windows 7 Firefox browser.
I thank you very much for the help that I get I would like to ask to send any links where it is poorly explained
<script>
// on click search results...
$('body').on('change', '#ean', function() {
var value = $("#ean").val();
if (value.length != 0) {
//alert(99933);
searchData(value);
} else {
$('#search-result-container').hide();
}
});
// This function helps to send the request to retrieve data from mysql database...
function searchData(val){
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="app/ajax-artstk/preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Please Wait...</span></div>');
$.post('app/ajax-artstk/controller.php',{'ean': val}, function(data){
if(data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'><div class=\"alert alert-danger\" role=\"alert\">No Result Found...</div></div>");
}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
});
}
</script>

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.....
}

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