ajax form not submitting handler expecting submit name attribute - javascript

I'm having a little problem getting a form to submit via ajax. I think it's one of two problems:
leads.py (which I am able to view, but do not have the ability to modify) is expecting a submit input name of name="submitButtonName" and because I am using e.preventDefault(); to disable normal form submitting the form is not being handled by the handler when submitted.
It could be possibly that the data being serialized is wrong, when i output it to console it looks like this which appears to be duplicated:
first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com&remarks=&first_name=Frank&last_name=TheTank&email_addr=frank%40thetank.com
any suggestions?
here is the full script:
<!-- Defines element markup -->
<dom-module id="landing-modal">
<template>
<div id="landing-modal" class="modal hide fade" tabindex="-1" role="dialog">
<div class="modal-body">
<p class=lead>
To view this listing, please provide us with some basic contact information...
</p>
<form class="form-horizontal lead-form" method="post" action="/leads/buy">
<div class="control-group">
<label class="control-label">Required Information</label>
</div>
<div class="control-group">
<label class="control-label">First Name</label>
<div class="controls">
<input type="text" name="first_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Last Name</label>
<div class="controls">
<input type="text" name="last_name" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<label class="control-label">Email</label>
<div class="controls">
<input type="email" name="email_addr" value="" required="" class="style-scope lead-form">
</div>
</div>
<div class="control-group">
<div class="controls">
<input style="display:none;" type="text" name="remarks" value="" />
<input type="reset" value="Reset" name="reset" class="btn">
<input class="btn btn-primary" type="submit" name="submitButtonName" value="Submit" />
</div>
</div>
</form>
</div>
</div>
</template>
<script>
$(document).on('submit', '.lead-form', function(e) {
$.ajax({
url: $('.lead-form').attr('action'), //gets the action url
type: $('.lead-form').attr('method'), //gets the form method post
data: $('.lead-form').serialize(), //creates the form submit date eg. FirstName=Mickey&LastName=Mouse
success: function(html) {
console.log($('.lead-form').serialize());
}
});
e.preventDefault(); //prevents the submit input from being submitted normally
});
Polymer({
is: 'landing-modal',
created: function() {},
ready: function() {},
attached: function() {},
detached: function() {},
attributeChanged: function(name, type) {}
});
</script>
</dom-module>
edit::
I tried to add
<input type="hidden" name="submitButtonName" />
<input class="btn btn-primary" type="submit" name="submit" value="Submit" />
which results in a 500 error in console
server side code:
if "submitButtonName" in kwargs:
errors = []
if not kwargs['first_name']:
errors.append("Please enter your first name.")
if not kwargs['last_name']:
errors.append("Please enter your last name.")
if not kwargs['email_addr']:
errors.append("Please enter your email address.")
if errors:
error_msg = "<ul>" + "".join([
"<li>"+x for x in errors
]) + "</ul>"
result['error_msg'] = error_msg
else:
save = True
if save:
# 'remarks' is an invisible field that can only get filled in by
# spam bots, so if there's a value in it, ignore the submission.
if kwargs['remarks']:
import sys
sys.stderr.write("Ignoring spam submission: %r\n" % ([mode,kwargs],))
else:
self.save_form(mode, kwargs)
raise cherrypy.InternalRedirect("/leads/thankyou/"+mode)
result.update(self.form.render(values))
if mode=="C":
result.update(self.cmaform.render(values))
if mode=="E":
result.update(self.contactform.render(values))
return result

Related

When I use Inputmask for Input tab key is blocked

When I use inputmask for my form input elements TAB Key not working. I can't switch with other input via tab key. I want use TAB key for switch via inputmask
HTML FORM
<form class="validate-form mt-2 pt-50" action="KisiEkle" enctype="multipart/form-data" method="POST">
<div class="modal-body">
<label>TC: </label>
<div class="mb-1">
<input type="text" id="TC" name="TC" placeholder="TC bilgisi" class="form-control" autocomplete="off" required="required" />
</div>
<label>Ad Soyad: </label>
<div class="mb-1">
<input type="text" id="AdSoyad" name="AdSoyad" placeholder="Ad Soyad" class="form-control" autocomplete="off" required="required" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Ekle</button>
</div>
</form>
JAVASCRİPT CODE
$(document).ready(function () {
$("#TC").inputmask("*{11,11}", { clearIncomplete: true, greedy: false });
});
<script src="~/assets/js/jquery.inputmask.min.js"></script> //2022 Robin Herbots

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

Check if an input is empty in form

i have a dynamic form so i have no idea which kind of input there will be every time and i need to handle that, so i've done something like this
<div id="repond-questionnaire" class="modal fade in" style="display: block;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Questionnaire de Test</h4>
</div>
<div class="modal-body" id="questionnaire_here">
<form method="post" id="questionnaire_form">
<div class="form-group">
<label for="text"><h3>Who are you?</h3></label>
<textarea type="text" name="80" class="form-control" rows="3" placeholder="Text..." required="" value=""></textarea>
</div>
<div class="form-group">
<label for="focusedInput"><h3>How old are you?</h3></label>
<input type="number" name="81" class="form-control" placeholder="Number..." required="" value="">
</div>
<div class="form-group">
<label for="focusedInput"><h3>What is your email?</h3></label>
<input type="email" name="82" class="form-control" placeholder="Email..." required="" value="">
</div>
<div class="form-group">
<label for="focusedInput"><h3>Do you like our website?</h3></label>
<div class="radio">
<label class="input-lg"><input type="radio" name="83" value="Oui">Oui</label>
</div>
<div class="radio">
<label class="input-lg"><input type="radio" name="83" value="Non">Non</label>
</div>
</div>
<input type="submit" name="sumbit" id="sumbit" value="Sumbit" class="btn btn-success"></form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="close" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#repond-questionnaire').on('click', '#sumbit', function() {
// here i need to check if all inputs are empty or not
//check if they have a valid input or not for security
//because after i will send everything and upload them to the data base
$.ajax({
url: "user/sumbit_answers.php",
method: "POST",
data: $('#questionnaire_form').serialize(),
beforeSend: function() {
$('#sumbit').val("Sumbiting...");
},
success: function(data) {
$('#questionnaire_form')[0].reset();
if (data == 'exit_failure') {
alert("something wrong happened");
} else {
$('#questionnaire_here').empty();
$('#questionnaire_here').html(data);
}
}
});
});
$('#repond-questionnaire').on('click', '#close', function(event) {
$('#questionnaire_here').empty();
});
});
</script>
and i'm obliged to do this because somehow the events of the form are blocked ( even though i'm not using event.preventdefault(), my form input are all like this
<input type='$type' name='$row[cid]' class='form-control' placeholder='$type...' required value=''>
Given that required attribute is already set at <input> elements within <form>, you can use .checkValidity() of <form> element.
Additionally you can include pattern attribute with RegExp [^\s]+ to require at least a single character at <input> elements. Adjust RegExp to meet requirement.
<form name="form">
<input name="input1" type="text" pattern="[^\s]+" required>
<input name="input2" type="text" pattern="[^\s]+" required>
<input type="submit">
</form>
<script>
document.forms.form.querySelector("[type=submit]")
.onclick = function() {
console.log(this.form.checkValidity());
// if (this.form.checkValidity()) { /* all <input> elements have `.value */ }
// else { /* all <input> elements do not have `.value */ }
}
</script>
var text_input=$("[type=text]");
var password_input=$("[type=password");
var radio_input=$("[type=radio]");
var checkbox_input=$("[type=checkbox]");
var select=$("<select>");
var textarea=$("<textarea>");
Then you have to do for loop for each one to check and apply your validation according to that field
Call ajax after validation (the following link will help you)
jQuery Form Validation before Ajax submit

Email validation for specific domain name

I have the following form. I want to validate the email field .it should only contain for domain name "#somename.com " when the user clicks submit.
The mail should only be validated when the check box is clicked to show the email field.
If the email is invalid i want to prevent submission
<form class="form-horizontal" id="rForm" data-toggle="validator" role="form">
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<label class="checkbox-inline col-xs-10">
<input type="checkbox" ID="chkbx"> Email
</label>
</div>
</div>
<div class="form-group email">
<div class="col-xs-offset-3 col-xs-8">
<div class="col-xs-8">
<input type="text" class="form-control " placeholder="Enter email">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<input type="reset" class="btn btn-default" id="rset" value="Reset">
<input type="submit" class="btn btn-primary" id="submit" value="Submit">
</div>
</div>
</form>
JS
$("#submit").on('keypress click', function(e){
e.preventDefault();
$('#chkbx').hide();
$('#chkbx').click(function () {
// This will show / hide your element accordingly
$('.email').toggle();
});
});
Checkout JavaScript RegEx to determine the email's domain (yahoo.com for example). You can use that and augment your example:
$('#chkbx').click(function() {
// This will show / hide your element accordingly
$('.email').toggle();
});
$("#submit").on('click', function(e) {
e.preventDefault();
if ($('#chkbx').is(':checked')) {
// https://stackoverflow.com/questions/3270185/javascript-regex-to-determine-the-emails-domain-yahoo-com-for-example
console.log(/#testdomain.com\s*$/.test($('#email_input').val()));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal" id="rForm" data-toggle="validator" role="form">
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<label class="checkbox-inline col-xs-10">
<input type="checkbox" ID="chkbx" checked>Email
</label>
</div>
</div>
<div class="form-group email">
<div class="col-xs-offset-3 col-xs-8">
<div class="col-xs-8">
<input id="email_input" type="text" class="form-control " placeholder="Enter email">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-8">
<input type="reset" class="btn btn-default" id="rset" value="Reset">
<input type="submit" class="btn btn-primary" id="submit" value="Submit">
</div>
</div>
</form>
Use the following function to test for your email.
EDIT:
You first need to add a name= and id= to your email input field.... So what you want to do is:
<input type="text" class="form-control " placeholder="Enter email" name="email" id="email">
and then do:
function testEmail(string) {
var regex = /.+#somename.com$/i;
return regex.test(string);
}
//testEmail("nope#test.com"); // false
//testEmail("what#somename.com.other"); //false
//testEmail("yeah#somename.com"); //true
//testEmail("#somename.com"); // false
$('form').submit(function(e){
var values = $('form').serialize();
if(!testEmail(values.email))
e.preventDefault();
// your submission code goes here.
})

Form gets submitted even if the required fields are left empty in angular JS

I am newbie to angular JS and i have created a form which is
HTML
<div data-ng-controller="ReservationController"
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-10">
<label>Guest Name</label>
<input type="text" class="form-control" placeholder="" ng-model="res_guest_name" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>Phone</label>
<input type="phone" class="form-control" ng-model="res_member_phone">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>FAX</label>
<input type="phone" class="form-control" ng-model="res_member_fax">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<label>Email</label>
<input type="email" class="form-control" ng-model="res_member_email" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-8 col-sm-10">
<button type="submit" class="btn btn-success" ng-click="res_save()">Save Changes</button>
</div>
</div>
</form>
</div>
CONTROLLER
function ReservationController($scope, $http, $cookieStore,$location,$filter) {
$scope.res_save = function()
{
var save_res ="https://pbg.com/save_form.html?contactid="+conId+"&token="+token+"&id="+$scope.resId+"&page=edit&guest_name="+$scope.res_guest_name+"&phone="+$scope.res_member_phone+"&fax="+$scope.res_member_fax+"&email="+$scope.res_member_email;
$http.get(save_res).success(function(response) {
alert('success');
});
}
}
My form gets submitted even after the required fields are left empty. it shows the error, then it gets submitted.
Obviously it will submit the form you didn't handled the submission of form.You just managed the errors :-)
Use ng-disabled="myForm.$invalid"
where myForm is the name field on form
<form class="form-horizontal" name="myForm" role="form">
<button type="submit" class="btn btn-success" ng-disable="myForm.$invalid" ng-click="res_save()">Save Changes</button>
If you don't want the button to be disable till then you can use
<button type="submit" class="btn btn-success" ng-click="res_save(myForm.$valid)">Save Changes</button>
And in controller
$scope.res_save = function(valid)
{
if(valid){
var save_res ="https://pbg.com/save_form.html?contactid="+conId+"&token="+token+"&id="+$scope.resId+"&page=edit&guest_name="+$scope.res_guest_name+"&phone="+$scope.res_member_phone+"&fax="+$scope.res_member_fax+"&email="+$scope.res_member_email;
$http.get(save_res).success(function(response) {
alert('success');
});
}
}
You are not checking for Form valid state before saving it , don't expect angular to magically stop saving when form is invalid.
You should look into the documentation for ng-submit. If you move the res_save function into an ng-submit on the form (and removed the ng-click on the submit input) it will validate against required fields, prevent execution of the function until they are valid.

Categories

Resources