What is the purpose of this function's parameter? - javascript

I would like to use a validate js plugin for a form (contact form with no refresh). I found this code below, where its author uses submitHandler key to send e-mails via AJAX and PHP. As the value there is a function function(form) { ... }. Could You tell me what is the purpose of the form parameter inside function(form)? The author doesn't even use it inside that function.
JS CODE:
$().ready(function() {
// validate the comment form when it is submitted.
$("#actualForm").validate({
focusInvalid: false,
onkeyup: true,
rules: {
// simple rule, converted to {required:true}
name: "required",
comment: "required",
email: {
required: true,
email: true
},
},
submitHandler: function(form) {
var name = $('input[name="name"]').val();
var email = $('input[name="email"]').val();
var comment = $('input[name="comment"]').val();
var params = {
"name": name,
"email": email,
"comment": comment,
};
console.log(data);debugger;
$.ajax({
url: 'email.php',
data: params,
type: 'POST',
dataType: json,
success: function (data) {
if (data.status) {
//Give success log to user
} else {
//Do something
}
}
});
}

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

If user manipulates the form id what is the best practice to secure it or stop this?

If user changes the formID what should i do to make the ajax call and jquery validation success.
<form id="formID" action="">
(function ($, W, D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function ()
{
$("#formID").validate({
rules: {
input:"required",
},
messages: {
input: "required",
},
submitHandler: function (form) {
var form = $('#formID')[0];
var formData = new FormData(form);
$.ajax({
type: 'post',
url: '/',
data: formData,
contentType: false,
processData: false,
success: function(data) {
if (data.response == true) {
alert('true');
} else {
alert('false');
}
}, error: function (jqXHR, exception) {
console.log(jqXHR.status);
}
});
}
});
}
}
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
Just remove var form = $('#formID')[0]; in the submitHandler. The form element is already exposed as an argument
The plugin will have already initialized before an ID could be changed by user in console and probably before any userscript or browser extension also
Changing an ID does not affect events already attached to that element.
Beyond that you can't control what a user does in their browser and just need to make sure your back end is secure

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

unable to send data via this.serialize

I am using following function to validate and send data to the php server:
$(document).ready(function () {
$(function() {
// Setup form validation on the #register-form element
$("#register_form").validate({
// Specify the validation rules
rules: {
register_username: "required",
register_password: "required",
register_email: {
required: true,
email: true
},
register_confirm_password: {
required: true,
equalTo: '#register_password'
},
},
// Specify the validation error messages
messages: {
register_username: "Please enter your username",
register_password: "Please enter your password",
register_confirm_password: {
required: "Please provide a password",
equalTo:"Please enter password same as above."
},
register_email: "Please enter a valid email address",
},
submitHandler: function(form) {
var pdata = $(this).serialize();
alert(pdata);
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(this).serialize(),
dataType : 'json',
success: function(data) {
if (data.success){
console.log("Form is submitted.data is" + data.success);
$.each(data, function() {
$.each(this, function(k, v) {
console.log("key; " + k);
console.log("value; " + v);
});
});
}
else
{
console.log("The data returned is:" + data.success);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return false;
},
});
});
});
All the validation works, but the issue is with the line:
var pdata = $(this).serialize();
I am getting empty pdata:
alert(pdata);
I don't know why the data is not serialized here. Please help me to solve this.
Don't serialize $( this )
Try serializing the form instead.
$( "#register_form" ).serialize();
$(this) isn't what you think it is anymore. It's not #register_form, but instead the submitHandler function.
If you do console.log(pdata) you should see the function definition in your console.
The scope of the submitHandler function is not the form element, so this is not pointing to the element you require. It does however provide you with a parameter, which you've named form, that you can use instead, like this:
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(form).serialize(),
// your code...

JavaScript not working in MVC web application

I have a ASP.NET MVC application and I have a few entries on the page that user can change and click Save and I go save those entries. My problem: It works fine for some entries and for other entries it just doesn't go in the controller Save function to do the save.
My code:
function DoSave() {
$("#pisave").attr("disabled", true);
var pid = $("#personid").val();alert(pid);
var firstname = $("#fname").val();alert(firstname);
var lastname = $("#lastname").val();alert(lastname);
var plz = $("#zip").val();alert(plz);
var ort = $("#city").val();alert(ort);
var bday = $("#birthdate").val();alert(bday);
var strasse = $("#street1").val(); alert(strasse);
var emailtext = $("#email").val();alert(emailtext);
var url = "#(Url.Action("SavePersonInfo", "Info"))";alert("URL");
$.ajax({
url: url,
data: { personid: pid,fn: firstname, ln: lastname, email: emailtext, zip: plz, city:ort, birthday: bday, street:strasse },
success: function () {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function () {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});
}
All alerts are displayed in all the cases. Only for some it goes to SavePersonInfo and for others it doesn't go in there. Any ideas what might be wrong?? Can it be validation issue for the entries?
The model binder fails to parse your date, change to post:
$.ajax({
type: "POST",
url: url,
data: { personid: pid,fn: firstname, ln: lastname, email: emailtext, zip: plz, city:ort, birthday: bday, street:strasse },
success: function() {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function() {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});​
Read more about the problems with dates in asp.net-MVC
Note that you can add all the elements a class and use the serialize function:
$.ajax({
type: "POST",
url: url,
data: $('.theClass').serialize(), // <=============
success: function() {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function() {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});​

Categories

Resources