Bootsrap Modal ajax save multiple record, bootstrapValidator - javascript

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

Related

How do I reinitialise jquery validation after loading form through ajax

I am loading a form via an ajax call. On the form I need to use jquery validation to validate the one text area.
The validation call is at the bottom of the page, but because the form isn't present when the page loads, I need to re-initalise it when the form has been loaded.
This is the code for the jquery validation:
class OpAuthSignIn {
static initValidationNotes() {
jQuery('.js-validation-notes').validate({
errorClass: 'invalid-feedback animated fadeInDown',
errorElement: 'div',
errorPlacement: (error, e) => {
jQuery(e).parents('.form-group > div').append(error);
},
highlight: e => {
jQuery(e).closest('.form-group').removeClass('is-invalid').addClass('is-invalid');
},
success: e => {
jQuery(e).closest('.form-group').removeClass('is-invalid');
jQuery(e).remove();
},
rules: {
'notefield': {
required: true,
minlength: 1
}
},
messages: {
'notefield' : 'Enter some details for the note'
}
});
}
static init() {
this.initValidationNotes();
}
}
// Initialize when page loads
jQuery(() => { OpAuthSignIn.init(); });
Then this is my ajax call script. I have commented where I need to initilise the validation:
function openNotes(testID){
var dataString = 'pupilID=<?=$pupilID?>&testID='+testID+'&forename=<?=$forename?>';
console.log("datastring: "+dataString);
$.ajax({
type: "POST",
url: "note_sidebar.php",
data: dataString,
cache: false,
success: function(html) {
console.log("html returned: "+html);
if (html!="Error"){
document.getElementById("sidebarTitle").innerHTML = "Notes";
document.getElementById("sidebarContent").innerHTML = html;
//I need to now initialise the form
}else{
swal("Opps!", "There was an error loading the notes", "warning");
}
}
});
}

jquery conditional form submit

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.

Bootstrap Validator - Send all input field values to remote PHP file

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 }

jQuery is not working with my form in popover

I want to create a form inside a popover and use jQuery and Ajax to submit the form(do some calculation while submitting the form). But somehow jQuery is not working at all. I'm using ruby on rails.
Here is my code on the view:
%a.btn.btn-small{:id => "example", "data-toggle" => "popover", :type => "button"}
%i.icon-calendar
.head.hide Do Something
.content.hide
=form_for :object, action: '#', :html => { :class => "form", remote: true} do |c|
=c.number_field :var_1
=c.number_field :var_2
%buttion.btn.btn-default{id: "submit", type: "button"}Click
Here is my code in js and jQuery under app/assets/javascript,
$(function () {
$('#example').popover({
html : true,
title: function () {
return $(this).parent().find('.head').html();
},
content: function () {
return $(this).parent().find('.content').html();
}
}).popover('show');
});
$(function(){
$('.form').submit(function(e) {
alert(1);
e.preventDefault()
var datastring = $(this).serializeArray();
datastring.push({name:"post", value:"Post"});
var request = $.ajax({
type: "POST",
url: $(this).attr('action'),
data: datastring});
request.success(function(data) {
console.log(data);
})
});
});
When I click "Click" button, there is even no alert(1) showing up, so i think the jQuery is not working but I can't work out what is going wrong?
Use this instead, this will bind the submit event in ajax loaded content
$('body').on('submit', '.form', function(){
# your code
});
if you follow the best practices then you should be writing jQuery like this :
$(document).ready(function(){
$('body').on('submit', '.form', function(){
// your code
});
});

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

Categories

Resources