Proper way to check if form is empty in Emberjs - javascript

I am using HTML5 validation in my form which is like this,
<script type="text/x-handlebars" id="project">
<div class="row">
<div class="span6">
<div class="well well-small">
<p style="text-align: center">
You can create a new Project by filling this simple form.
</p>
<p style="text-align: center"> Project Name should be minimum 10 characters & There's no limit on
Project Description.
</p>
</div>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="projectname">Project Name: </label>
<div class="controls">
{{!view App.TextFieldEmpty}}
<input type="text" name="projectname" id="projectname" required title="Project Name is Required!" pattern="[A-z ]{10,}" placeholder="Enter Project Name"/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="projectdesc">Project Description:</label>
<div class="controls">
<textarea rows="3" id="projectdesc" name="projectdesc" placeholder="Enter Project Desc"
required="Description Required"></textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn" {{action 'createNew'}}>Add Project</button>
</div>
</div>
</form>
</div>
</div>
</script>
And here's what I have tried to do in App.js,
App.ProjectController = Ember.ArrayController.extend({
actions : {
createNew : function() {
if (!("#project form.form-horizontal") === "") {
App.Project.createNew();
}
}
}
});
App.ProjectRoute = Ember.Route.extend({
});
App.Project.reopenClass({
createNew : function() {
dataString = {
'projectname' : $("#projectname").val(),
'projectdesc' : $("#projectdesc").val()
};
console.log('check');
$.ajax({
type : "POST",
url : "http://ankur.local/users/createNewProject",
data : dataString,
dataType : "json",
success : function(data) {
console.log('success');
}
});
return false;
}
});
As you can see in the actions, I am trying to check if form is not empty then do a Ajax POST. But the problem I am encountering is even if the form is not empty, the button doesn't do anything.
Moreover, if I am including the whole form, it will check checkboxes as well? (I want to have one as well)
What I can do to make sure that user doesn't submit empty form?

This is more of a JS/jQuery question than an Ember one. You should look at the jQuery val() function.
You should validate your form inputs in your view, where you can access the <input elements. Furthermore (!("#project form.form-horizontal") === "") is missing the jQuery selector $.
App.ProjectView = Ember.View.extend({
actions : {
createNew : function() {
if (!(this.$("#projectname").val() === "")) {
App.Project.createNew();
}
}
}
});
There might be some other kinks in your code, it would be helpful if you could put together a jsFiddle - that way it makes it much easier for us to help you and you.

Okay I am going to answer my own question & it seems to be working.
Here's what I did:
App.ProjectController = Ember.ArrayController.extend({
actions : {
createNew : function(event) {
$(":text, :file, :checkbox, select, textarea").each(function() {
if ($(this).val() === "") {
alert("Empty Fields!!");
} else {
App.Project.createNew();
event.preventDefault();
}
});
}
}
});

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

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

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.

JavaScript - Bootstrap Validator

I am using this plugin: Plugin Link
I am trying to validate, if at least one checkbox out of a checkbox group has been selected. The plugin doesn't support such a functionality. Therefore i googled, and found this, by the plugin author himself: Discussion Link and a working implementation here: Example
I tried implementing it and failed. This is what i have so far:
<div class="col-lg-9">
<?php
// Input form for choosing complaints
foreach (Complaints::getComplaints() as $complaint) {
?>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]"
data-error="Try selecting at least one...">
<?= Helper::sanitize($complaint->getName()) ?>
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<?php
}
?>
</div>
Plus this is the copied JS Function, that should do the magic...:
<script>
$('[data-toggle="validator"]').validator({
custom: {
chkgrp: function ($el) {
console.log("Some debug output, if it is triggered at all" + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
return $checkboxes.is(":checked");
}
},
errors: {
chkgrp: "Choose atleast one!"
}
}).on("change.bs.validator", "[data-chkgrp]", function (e) {
var $el = $(e.target);
console.log("Does is even work? " + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
$checkboxes.not(":checked").trigger("input");
});
So yeeh. Nothing happens, if i try to run this. None of my debug output is printed in the console. Nothing. The form itself also consists out of some password fields and text fields, the checkbox group - generated in the foreach loop - is just one part of it. The validator works for the text and password fields, but does exactly nothing for the checkbox group. Any ideas?
Thanks! :)
I just tried to make it neat.
please checkout the solution:
Reference: http://1000hz.github.io/bootstrap-validator/
$('#form').validator().on('submit', function (e) {
var validate = false;
$("input[type='checkbox']").each(function(index,e){
if($(e).is(':checked'))
validate = true;
});
if(validate){
//valid
$('.with-errors').html(' ');
} else {
$('.with-errors').html('not valid');
}
//if (e.isDefaultPrevented()) {
// handle the invalid form...
//} else {
// everything looks good!
//}
})
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form role="form" data-toggle="validator" id="form" action="" method="POST">
<div class="col-lg-9">
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste1
</label>
<div class="help-block "></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste2
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste3
</label>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" >Validade</button>
</form>

jQuery .submit() .ajax() have to click send button two times to get the correct response

I have a form with 5 fields that i am sending with AJAX to a PHP Script that does some simple validation and returns a string.
I have made a little jQuery script for the actual submission, and when i try to send the form i have to click the send button two times.
Update: Url to live site: http://www.dan-levi.no/new/#!/Kontakt
Here are some code:
HTML
<form id="contact_form" class="form-horizontal" action"includes/contact.php" method"post">
<div class="control-group">
<label class="control-label" for="contact_name">Ditt navn og evt. bedrift</label>
<div class="controls">
<input type="text" class="input-large" id="contact_name" name="contact_name" placeholder="Ditt navn og evt. bedrift" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_email">E-post</label>
<div class="controls">
<input type="email" class="input-large" id="contact_email" name="contact_email" placeholder="E-post" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_tel">Telefon</label>
<div class="controls">
<input type="tel" class="input-large" id="tel" name="contact_tel" placeholder="Telefon" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_subject">Emne</label>
<div class="controls">
<input type="text" class="input-large" id="subject" name="contact_subject" placeholder="Emne for melding" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_desc">Din beskjed</label>
<div class="controls">
<textarea rows="10" class="input-large" id="contact_desc" name="contact_desc" placeholder="Din beskjed"></textarea>
</div>
</div>
<div class="text-error pull-right" id="error_message"></div><br>
<input class="btn btn-large pull-right" type="submit" name="" value="Send" /><br>
</form>
javaScript
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
})
.done(function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
})
e.preventDefault();
});
});
PHP
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_tel = $_POST['contact_tel'];
$contact_subject = $_POST['contact_subject'];
$contact_desc = $_POST['contact_desc'];
if ($contact_name == '' || $contact_email == '' || $contact_tel == '' || $contact_subject == '' || $contact_desc == '') {
echo "empty";
die();
}
echo $contact_name.'<br><br>';
echo $contact_email.'<br><br>';
echo $contact_tel.'<br><br>';
echo $contact_subject.'<br><br>';
echo $contact_desc.'<br><br>';
I cant find out why i have to click the button two times, i have tried some trial and error, read the forum for answers. I tried to serialize the form outsite the submit function, i just cant get this to behave the way i want. All help is greatly appreciated.
Oh, worth to mention. The actual response is that the fields are empty (php validation) the first time i click, but the second time it works as it should.
Make the ajax call using a regular input button instead of a submit button.
$("#button").click(function () { ... ajax ... }
I'm not sure if it makes a difference but have you tried putting what you want to happen afterwards in a success callback?
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
e.preventDefault();
});
});
I'm guessing it's because the default action (submit the form) is processing before your $.ajax request. Try making e.preventDefault() first in your submit callback.
$(document).ready(function() {
$('#contact_form').submit(function(e) {
e.preventDefault();
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
});
});

Categories

Resources