jquery conditional form submit - javascript

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.

Related

multiple addEventListener on submit for the same form

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;
});
});

How can I replace prompt with dialog and promises JS

I have next method that is triggered on button click
function approveDay(URL, dateDay, action, cNT) {
var message = '';
if (action === 'false') {
message = prompt('Enter notes : ', '');
if (message === null) {
return false;
} else if (message.trim() === "") {
showMessage(2,
"The status of the timesheet cannot be changed to \"Not approved\" if no comments are specified!");
return false;
}
}
var data;
if (cNT === null) {
data = addAntiForgeryToken({ UID: userId, dateDay: dateDay, action: action, message: message });
}
else {
data = addAntiForgeryToken({ UID: userId, dateDay: dateDay, action: action, message: message, cNT: cNT });
}
blockUI();
$.ajax({
type: 'POST',
url: URL,
data: data,
success:
function (result) {
showMsg(result);
location.reload();
},
error: function (xhr, textStatus, errorThrown) { AjaxErrMessage(xhr, textStatus, errorThrown); }
});
return false;
}
I need to remove prompt and replace it with dialog box, which contains input field for message and button for add that saves this message. But also I need to stop the execution of the function. I know than promises can help me with my problem.
How can I implement this solution or solution without promises. My dialog box initialize function is below
function initModalWindow() {
$("#RejectNotesBlock").dialog({
width: 500,
modal: true,
close: function (event, ui) {
$("#RejectNotesBlock").dialog("close");
}
});
}
Thank you.

Bootsrap Modal ajax save multiple record, bootstrapValidator

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! :)

Stopping Javascript From Submitting Form Multiple Times

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;
});

How to toggle JQuery .$post url

In my program i have written the jquery like below:
$(document).ready(function() {
$("#toggle").click(function() {
$.post("/project/addhighlight", {
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
var dataconverted = jQuery.parseJSON(data);
$("#mytext").text(dataconverted);
if (status == "success") { }
});
});
})
What i want to do is to change the $.post url(/project/addhighlight) to the one returned by the backend method once the post is success.
Can any one please advice on how to do it?
You can store the url in a variable which you can update in the callback:
var postUrl = '/project/addhighlight';
$("#toggle").click(function() {
$.post(postUrl, {
name: "Donald Duck",
city: "Duckburg"
},
function(data, status) {
$("#mytext").text(data);
if (status == "success") {
postUrl = data.updatedPostUrl; // your property here...
}
});
});
Note that jQuery.parseJSON(data) is not needed, as jQuery will automatically parse a JSON response when it detects one.

Categories

Resources