I have a form which I am submitting to Parse and after I added in some client side validation, it keeps double submitting to the database.
I have already read some of the other Stack posts on this topic and have adjusted my code but it still is happening (I just started learning JS). Any advice on how to fix this would be appreciated. Thanks!
$(document).ready(function() {
Parse.initialize("XXXX", "XXXX");
$('#commentForm').bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
username: {
message: 'The username is not valid',
validators: {
notEmpty: {
message: 'The username is required and cannot be empty'
}
}
}
}
});
$("#commentForm").on("submit", function(e) {
$(this).submit(function() {
return false;
});
e.preventDefault();
console.log("Handling the submit");
//add error handling here
//gather the form data
var data = {};
data.username = $("#username").val();
data.password = $("#password").val();
data.passwords = $("#password").val();
data.email = $("#email").val();
// data.area = $("#area option:selected").val();
// data.comments = $("#comments").val();
var comment = new Parse.User();
comment.save(data, {
success:function() {
console.log("Success");
alert("Thanks for signing up!");
},
error:function(e) {
console.dir(e);
}
});
});
});
It's probably because of the second submit function inside your form submit function, so try to remove:
$(this).submit(function() {
return false;
});
Related
My stripe checkout page i have a section in the from for billing information using html (none stripe form)
when a user submits the form, this ajax is fired, to validate the billing information section (name, email etc)
$(document).ready(function () {
var $form = $("#payment-form");
$form.on("submit", function (event, messages) {
event.preventDefault();
$.ajax({
"type":"POST",
"url":$form.attr('action'),
"data":$form.serialize(),
"beforeSend":function( xhr ) {
$('#stripe-isValid').val('false');
},
"dataType":"json",
"success":function(data){
if(data !== 'undefined' && data.validate == 'success') {
$('#stripe-isValid').val(data.validate);
}
},
});
return false;
});
});
if the form is valid, the input value is changed from false to success
<input type="text" name="stripe-isValid" id="stripe-isValid" value="success" />
now if the validation is successful, i have 2 addEventListener for 2 different types of payments.
for card payments (if user chooses to pay by card)
const cardElement = elements.create('card', { hidePostalCode: true, style: style });
cardElement.mount('#card-element');
//check if card is valid
cardElement.on('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
Swal.fire({
title: "Error!",
text: event.error.message,
type: "error"
});
} else {
displayError.textContent = '';
}
});
const paymentForm = document.querySelector('#payment-form');
paymentForm.addEventListener('submit', function(e) {
if (document.getElementById('stripe-isValid').value == 'success' && document.getElementById('card-radio').checked) {
e.preventDefault();
stripe.confirmCardPayment(
paymentIntent, {
payment_method: {
card: cardElement,
},
},
).then(function(result) {
if (result.error) {
// Display error.message in your UI.
Swal.fire({
title: "Error!",
text: result.error.message,
type: "error"
});
return false;
...
...
...
}
});
for FPX payments (if user chooses to pay using FPX)
$("#payment-form").on("submit", function(e) {
if ($("#stripe-isValid").val() == "success" && $("#fpx-radio").is(":checked")) {
e.preventDefault();
...
}
});
so far, this logic flow works on my localhost.
validate form, return success on valid or false on invalid
if card payment selected and input value is success from step 1 ... run stripe logic
if FPX payment selected and input value is success from step 1 ... run stripe logic
Would having multiple on submits for the same form cause any issues? Even if i merge the stripe ones and have 2 instead of 3, would it would cause issues to some users, any better way to do this? Thanks
Why not combine them - processing after validation?
$(document).ready(function() {
var $form = $("#payment-form");
$form.on("submit", function(event, messages) {
event.preventDefault();
$.ajax({
"type": "POST",
"url": $form.attr('action'),
"data": $form.serialize(),
"beforeSend": function(xhr) {
$('#stripe-isValid').val('false');
},
"dataType": "json",
"success": function(data) {
if (data !== 'undefined' && data.validate == 'success') {
$('#stripe-isValid').val(data.validate);
}
if ($("#stripe-isValid").val() == "success" && $("#card-radio").is(":checked")) {
// process card
} else if ($("#stripe-isValid").val() == "success" && $("#fpx-radio").is(":checked")) {
// process fpx
} else {
// ?
}
},
});
return false;
});
});
I have problem with bootstrap modal form. For validate fields im using bootstrapValidator. My problem is that when i popup the modal and then close data from inputs are deleted, but when i popup again and fill the fields then send AJAX my script insert to DB multiple records.
<script>
$(document).ready(function () {
$(".bs-example-modal-lg").on('hidden.bs.modal', function (e) {
$("#ModalClientTransportowe").bootstrapValidator('resetForm', true);
});
});
</script>
<script>
$('.bs-example-modal-lg').on('shown.bs.modal', function () {
$(document).ready(function () {
$('#ModalClientTransportowe').bootstrapValidator({
message: 'This value is not valid',
excluded: [':disabled'],
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
company: {
validators: {
notEmpty: {
message: 'Proszę wprowadzić nazwe klienta'
}
}
},
}
});
}).on('success.form.bv', function (e) {
e.preventDefault();
var data = $("#ModalClientTransportowe").serialize();
$.ajax({
type: 'POST',
data: data,
url: "{{ path('saveClient') }}",
success: function (data) {
$('#hint').val(data);
$('.bs-example-modal-lg').modal('hide')
},
});
});
});
</script>
I think that's the problem is by calling ajax on every show.bs.modal action.
Can someone give advice about how can i do it to work propely ?
OK, the answer is very simple... i deleted on show event and everythink worked! :)
I am trying to update user profile. After user inserts his address and submits it converts it to latitude and longitude. I created a conditional statement: if GeocoderStatus is OK then change geoLocationOK = 1 else it is 0. When it is 1 then run the update function, but the latitude and longitude is not passed to formData. On second update click it is added. Any suggestion how can I include the latitude and longitude in formData?
Click to update
$(document).on("click", "#updateProfile", function (e) {
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log(latitude);
console.log(longitude);
userLatitude = document.getElementById('cityLat').value = latitude;
userLongitude = document.getElementById('cityLng').value = longitude;
geoLocationOK = 1;
console.log(geoLocationOK);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
geocodeAddress(geocoder);
if(geoLocationOK == 1){
updateProfile();
}else{
console.log("not ok");
e.preventDefault();
}
});
This is the update function
function updateProfile(){
console.log(geoLocationOK);
$('#rootwizard').formValidation({
framework: 'bootstrap',
excluded: [':disabled'],
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
live: 'enabled',
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
userPhoneNr: {
validators: {
notEmpty: {
message: 'Please insert phone nr'
},
regexp: {
regexp: /^[a-zA-Z0-9_]+$/,
message: 'Error'
}
}
},
}
}).on('success.form.fv', function(e, data) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray(),
files = $form.find('[name="userProfilePhoto"]')[0].files;
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
$.ajax({
url: $form.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
if(data.status == 'success'){
getProfileData();
}
},
error: function(jqXHR, textStatus, errorThrown, data){
console.log(jqXHR, textStatus, errorThrown, data);
}
});
// Now Destroy
function destroyFormValidation() {
var instance = $('#rootwizard').data('formValidation');
if (instance) {
instance.destroy();
}
}
destroyFormValidation();
});
}
Why you only can update on the second click is because on the first click you actually binding the form validation. Why not bind the form validation separately outside the function updateProfile .
And then inside updateProfile submit the form:
function updateProfile(){
$('#rootwizard').submit();
}
Get rid of
if(geoLocationOK == 1){
updateProfile();
}else{
console.log("not ok");
e.preventDefault();
}
and move the call to
updateProfile();
inside your
if (status === google.maps.GeocoderStatus.OK) { ... }
block.
You maybe also still need e.preventDefault(); in there somewhere as well (or you could change the updateProfile element to not be a submit button).
It looks like the geolocation function is asynchronous, which means it it executed in parallel to the other code. Therefore your if (geolocationOK == 1) is almost certain going to run before the function which sets the geolocationOK variable.
In any situation like this with async calls, if you have code which depends on the results of the async call, then that call must be executed within the "success" context of the async call.
I was wondering if there was a way to send all of my input field values to a remote PHP file using Bootstrap Validator.
To explain, I have two input fields in a log in form. I use Bootstrap Validator's remote validation on both of the input fields. Each validation only sends the requested input field's value and there is no access to the other input field via $_POST in the PHP back end.
I know that I can send data to the PHP back end with the data option, but I am unsure as to how the formatting would go if I were to send the values of different input fields in that section.
Here is a coding example.
$(document).ready(function() {
$('#login_form').bootstrapValidator({
fields: {
username: {
message: 'Invalid',
validators: {
remote: {
message: 'Invalid',
url: '/path/to/backend/',
data: {
password: // What do I put here?
}
}
}
},
password: {
message: 'Invalid',
validators: {
remote: {
message: 'Invalid',
url: '/path/to/backend/',
data: {
username: // What do I put here?
}
}
}
}
}
});
});
That coding example is one way to solve my problem and have both input field values submitted to the back end. If anyone has a solution to my problem with this method, or another way that I can go about giving all input field values to the back end, please let me know.
Thank you in advance for any help that you may give.
For sending any input field in your form to the backend, just call a validator function that recalls the values of the input fields in your form and assign them to a parameter with a descriptive name.
This parameter then can be accessed from POST (or from GET i you so configure it) in /path/to/backend.
You can see you code modified below.
I hope it will work for you. It's fully tested code.
Please send feedback.
$(document).ready(function() {
$('#login_form').bootstrapValidator({
fields: {
username: {
message: 'Invalid',
validators: {
remote: {
url: '/path/to/backend/',
data: function(validator) {
return {
password: $('[name="passwordNameAttributeInYourForm"]').val(),
whatever: $('[name="whateverNameAttributeInYourForm"]').val()
};
},
message: 'Invalid'
}
}
},
password: {
message: 'Invalid',
validators: {
remote: {
url: '/path/to/backend/',
data: function(validator) {
return {
username: $('[name="usernameNameAttributeInYourForm"]').val(),
whatever: $('[name="whateverNameAttributeInYourForm"]').val()
};
},
message: 'Invalid'
}
}
}
}
});
});
To send data to backend using bootstrap validator use this code.
$(document).ready(function() {
$('#student_view').bootstrapValidator({
// To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
container: 'tooltip',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
coursename: {
validators: {
notEmpty: {
message: 'Please select course name'
},
remote: {
url: 'abc.php', //path to backend
data: function(validator) {
return {
course: $('#course').val(), //sending dynamic data value
password: $('#password').val()
};
},
message: 'Invalid'
}
}
},
}
})
.on('success.form.bv', function(e) {
$('#student_view').data('bootstrapValidator').resetForm();
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
backend must return output in the following format
{ "valid": true } or { "valid": false }
I am new to javascript and jquery and I'm trying to submit a form which is validated using the jquery validation plugin using the enter key. This is my code but the form is not being submitted as the alert isn't showing when you press enter. I'm not sure what exactly is happening. I think the page is simply being reloaded when i press enter. There's certainly no validation
<script>
$(document).ready(function() {
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#invalid_' + element.attr('id'));
}
});
var validator = $("#login_form").validate({
rules: {
user_email: {
required: true,
email: true
},
password: {
required: true
}
},
messages:{
user_email:{
required:"Email required",
email: "Must be a valid email"
},
password: {
required: "Password required"
}
},
submitHandler: function(form) {
alert('submitted');
$.ajax({
type: "POST",
url: "ajax/check_login.php",
data: $(form).serialize(),
timeout: 3000,
success: function(resp) {
if (resp == 'error') {
$('#login_error').html('Invalid login');
} else {
load_user_area();
}
},
error: function(e) {alert('failed' + e);}
});
return false;
}
});
$(document).keydown(function(e) {
if (e.keyCode == 13) { $('#login_form').submit(); }
});
});
</script>
Thanks in advance for any help!