JQuery adds a comma when sending a variable to the server - javascript

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

Related

What is the purpose of this function's parameter?

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

Node.js/Mongoose/lodash - server response: User Validation Failed: path `foo` is required

The error message being received is:
"User validation failed: email: Path email is required., display_name: Path display_name is required."
The error name being sent back is: ValidationError.
The code for the ajax call is:
function submit_new_user(display_name, email, password){
let user_data = new New_User(display_name, email, password);
console.log(user_data);
$.ajax ({
dataType: 'JSON',
data: user_data,
method:'POST',
url: 'http://localhost:3001/user',
success: (res)=>{
console.log(res);
},
error: (xhr, ajaxOptions, thrownError)=>{
console.log(xhr, ajaxOptions, thrownError);
}
});
};
the console.log seen above prints:
New_User {display_name: "test", email: "test#test.com", password: "Passw0rd"}
The server route is:
app.post('/user', (req, res)=>{
let body = _.pick(req.body, ['display_name', 'email', 'password']);
let user = new User(body);
user.save().then(()=>{
return user.generateAuthToken();
}).then((token)=>{
res.header('x-auth', token).send(user);
}).catch((err)=>{
res.status(400).send(err);
});
});
This route works when pinged with Postman. The server supports cors.
The model is as follows:
var UserSchema = new mongoose.Schema({
display_name: {
type: String,
unique: true,
required: true,
validate: {
validator: (val)=>{
return /^[\w\s]+$/.test(val);
},
message: '{VALUE} is not a valid display name. Only
alphanumeric, upper and lower case characters are allowed.'
}
},
email: {
type: String,
required: true,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email.'
}
},
password: {
type: String,
require: true,
minlength: 6
},
tokens: [{
access:{
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
I'm still learning node.js. I was guided through the creation of the API, and am trying to build a front end on my own.
The object leaving contains the three value pairs - but the object arriving, before the server changes it, is empty. I'm at loss as to why.
SOLUTION: the problem was in the server-side bodyParser. I had forgotten to include the encoded url method. It was not parsing the JSON as it came in, since previously the API had only been tested using Postman there was no need to use the .urlencoded() method.

Pass variables to URL in ajax

I have the below ajax call in which I am trying to post the registration data directly to URL, but is there anyway I can store those variables and then pass it into the URL. Please help thank you in advance.
You can see the Script.js in this plunker
jquery:
$(function() {
/* Registration form for the website */
/* validation */
$("#register-form").validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
},
userName: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 8,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
},
messages: {
userName: "please enter a valid user name",
password: {
required: "please provide a password",
minlength: "password at least have 8 characters"
},
email: "please enter a valid email address",
cpassword: {
required: "please retype your password",
equalTo: "password doesn't match !"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm() {
var data = $("#register-form").serialize();
// var data={
// firstName: $('#firstName').val(),
// }
$.ajax({
url: 'http://localhost:8000?userName=&password=&firstName=&lastName=&email=',
type: 'POST',
data: data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success: function(data) {
if (data === 0) {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
} else if (data == 1) {
$("#btn-submit").html('<img src="btn-ajax-loader.gif" /> Signing Up ...');
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
});
url: 'http://localhost:8000?userName=&password=&firstName=&lastName=&email=',
type: 'POST',
data: data,
become
url: 'http://localhost:8000?' + data,
type: 'GET',
//data: data,
Your AJAX URL is wrong, you do not need to type in the full address. The Serialize method should do that for you. All you need is localhost:8000? + data. And as #zer00ne said, never use a GET if your sending in a password, it will show up on the URL. As a rule of thumb, anything sent in a form should be a POST request, unless some rare cases which I am not aware of.
My suggestion:
$.ajax({
url: 'http://localhost:8000?',
type: 'POST',
data: data,
This way your sending in your information to the proper place and securely.

Error: jQuery jquery.min.js?_=1420285687057:4 Uncaught TypeError: undefined is not a function

I have problem with jquery validate plugn and history API, when i click few times
i have error jquery.min.js?_=1420288991396:4 Uncaught TypeError: undefined is not a function, when I comment a fragment with validate, script works fine. How concat this script.
In file script.js i have:
$(document).ready(function(){
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
},
messages: {
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
},
submitHandler: function() {
var username=$("#usernameLogin").val();
var password=$("#passwordLogin").val();
var dataString = 'username='+username+'&password='+password+'&tag=login';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
if($("#rememberMe:checked").val()){
checkCookie(username);
}
window.location.href = "index.php";
}
else{
$("#error").html("<label class='error'>Wrong password or username!</label>");
console.log("Wrong password or username!");
}
}
});
}
return false;
}
});
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: {
required: true,
minlength: 3
},
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
}
},
messages: {
firstname: {
required: "Please enter your firstname",
minlength: "Your firstname must consist of at least 3 characters"
},
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
},
submitHandler: function() {
var username=$("#username").val();
var password=$("#password").val();
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
var dataString = 'username='+username+'&password='+password+'&firstname='+firstname+'&lastname='+lastname+'&email='+email+'&tag=register';
if($.trim(username).length>0 && $.trim(password).length>0){
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: dataString,
cache: false,
success: function(data){
if(data){
console.log(data);
$(".register_notification").html("<label class='error' style='background:#6DC066'>Register successfully!</label>");
}
else{
$(".register_notification").html("<label class='error'>Username already exists, please choose another one!</label>");
}
}
});
}
return false;
}
});
// propose username by combining first- and lastname
$("#username").focus(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
if (firstname && lastname && !this.value) {
this.value = firstname + "." + lastname;
}
});
$("footer a").click(function(e){
//e.preventDefault();
/*
if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content;
if commented, html5 nonsupported browers will reload the page to the specified link.
*/
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({url:pageurl,success: function(data){
$('#login_box').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
$(window).bind('popstate', function() {
if(!location.pathname.localeCompare('/login.php')){
$.ajax({url:location.pathname,success: function(data){
$('body').html(data);
}});
}
else{
$.ajax({url:location.pathname,success: function(data){
$('#login_box').html(data);
}});
}
});
From jQuery library:
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
it shows throw e.
I can't think of any reason why using the browser's "back" button would cause the JavaScript to fail. Everything should be cached and continue to work as before.
The error you're getting is similar to the error you'd get if you failed to include the plugin.
Here is how you're including the jQuery Validate plugin...
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
Notice how you're hotlinking to the plugin hosted on the developer's own domain. (likely for his demos and/or to download.) This error might be caused by a timing issue, the plugin not loading fast enough from this URL.
The developer has provided his plugin on two different free CDN services where "hotlinking welcome". So instead of leaching the plugin directly from his domain, try hotlinking to the CDN links provided here.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>

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 }

Categories

Resources