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

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 }

Related

Jquery Validation remote method always shows invalid

I am trying to validate an html function with django and the JavaScript FormValidation plugin. I want validation
to check if the inserted email already exists,
This is my validation remote
email: {
validators: {
notEmpty: {
message: 'email field can not be empty'
},
emailAddress: {
message: 'is not a valid email'
},
remote: {
message: 'email is already in use',
url: '/validate_email/',
type: 'post',
data: {
email: function() {
return $('#email').val();
}
},
},
},
},
The url calls to my view def which is
def validate_email(request):
email = request.GET.get('email', None)
data = not Vendors.objects.filter(email__iexact=email).exists()
if data is True:
data = "true"
else:
data = "false"
return JsonResponse(data, safe=False)
I am getting a correct "true" or "false" JsonResponse, but the message always shows that the email is already in use and keep asking me to correct it.
I tried passing the JsonResponse as true or false without "", also tried passing the JsonResponse as is_taken: true or is_taken: false.
In your Django view, you need to return a JSON response in the following format:
return JsonResponse({"valid": data})
The FormValidation plugin will understand that the email is valid if the response is "valid":true and invalid if the response is "valid": false.

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

JQuery adds a comma when sending a variable to the server

I am using the https://jqueryvalidation.org/ library for form validation. When passing a variable to the controller, a comma is added to the beginning of the string. I do not know why.
Validation code
$('#registrationForm').validate({
rules: {
username: {
nowhitespace: true,
required: true,
minlength: 6,
maxlength: 36,
remote : {
url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
type: "GET",
data: {
username: function() {
return $('#username').val();
}
}
}
},
And this is my controller
#GetMapping("/checkUsername")
public boolean checkUsername(#RequestParam("username") String username) {
System.out.println("User: " + username);
return !userService.existsByUsername(username);
}
In addition to checking what happens, I added a username display and when passing the username to the controller the result is the following
User: ,j
User: ,jo
User: ,jon
User: ,jonk
User: ,jonki
I did not enter this comma. He added himself at the beginning. Appears out of nowhere.
Why have you appended username to url part as well as data field in post data. It is a get request. Do not use post data in that scenario.
You need to remove from your validate code
data: {
username: function() {
return $('#username').val();
}
}
Your final code should be
$('#registrationForm').validate({
rules: {
username: {
nowhitespace: true,
required: true,
minlength: 6,
maxlength: 36,
remote : {
url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
type: "GET"
}
},
Or you could try :
remote : {
url: '/checkUsername',
type: "GET",
data: {
username: function() {
return $('#username').val();
}
}
}

Adding an onSubmit function in Semantic-ui validation form

Im upload files with a form so when the submit button is pressed, I need to inform the user with a loading button. This seems to not work.
JavaScript:
$('.ui.form').form({
fields: {
input1: {
identifier: 'input1',
rules: [{
type: "empty",
prompt: "input1 - This field is required"
}]
},
input2: {
identifier: 'input2',
rules: [{
type: "empty",
prompt: "input2 - This field is required"
}]
}
},
onSuccess() {
//$('.submit.button').addClass('loading')
console.log('Form submitting...')
}
});
I've left out the html just to focus on the JS. Removing on onSuccess(), will submit the form but not with the onSuccess() in. Am I going this the right way?
I do not believe there is a callback for onSuccess with form submit.
You should grab the values from your form and then use $.post and use the success callback.
$('.ui.form').submit(function() {
$.ajax({
type: "POST",
url: "url/to/server.php",
data: $(this).serialize(),
success: function() {
// callback code here
},
});
})

JQuery validation "remote" method response waiting message

I am using JQuery validation plugin "remote" method for Ajax based validation.
But I have to make some third party calls to verify data and it takes approx. 30 seconds.
So need to show some message to end user while data is getting processed by Ajax request. Can anyone help to achieve this?
You can see an example from below that i done:
jQuery Validate (Remote Method):
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: 'your-url-or-path-here.php',
cache: false,
dataType: 'POST', // Post, Get, Json, etc
data: {
field: $('.element').val()
}
beforeSend: function () {
$('.loading').css('display','none').show();
},
complete: function () {
$('.loading').hide();
}
}
}
}
});

Categories

Resources