HTML Form onsubmit not executing the external function - javascript

I have a HTML Form and on submit, a validate() function to be called.
The submit works fine, if the validate() function is within the "script" tag at the end of the "body" tag.
Otherwise, the submit doesn't call the validate() function when it is present in external js file, even though document.ready is used, as in https://jsfiddle.net/vg47127o/1/
HTML --
<form method="post" action="#" onsubmit="return validate()" name="loginForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="error-block"><span class="glyphicon glyphicon-exclamation-sign"> </span> <span class="error-msg"></span></p>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="username">username:
</label>
<div class="col-sm-9">
<input type="text" class="form-control digits-only" id="username" placeholder="Enter Username">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">Password:</label>
<div class="col-sm-9">
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" id="loginBtn" class="btn btn-default">Log In</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
SCRIPT --
$(document).ready(function() {
var displayError = function(error, msg) {
$(".error-block .error-msg").text(msg);
if (error === true)
$(".error-block").show();
else
$(".error-block").hide();
return true;
};
//Validating the input fields
var validate = function() {
var $username = $("#username").val(),
$password = $("#password").val();
if ($username === '' || $password === '') {
displayError(true, ' Username or Password cannot be empty. ');
return false;
} else if ($username.length < 6 || $password.length < 6) {
displayError(true, ' Username and Password should be a minimum of 6 characters. ');
return false;
} else {
displayError(false, ' ');
return true;
}
};
});
Am I missing out something here or What could be the reason for this.

Here's an updated fiddle that is working. You need to trap the submit() event if validate does not return true.
This is what you would include in your jQuery:
$("form").on("submit", function (event) {
if (!validate()) {
event.preventDefault();
}
});
Then your <form> tag would simply be <form method="post" action="#" name="loginForm" class="form-horizontal" role="form">
FYI
The reason for this is that when your validate() function is inside of your document ready, it is scoped to the document ready function, therefore, inline DOM event triggers do not have access to it. You have to set up the event handler inside the jQuery function, or declare your validate() function outside of your document ready function.

The validate variable is scoped to the anonymous function you put into $(document).ready. That means it can be accessed only from within that function and not from the page which lives in the global scope.
Add the event listener using the $(...).submit function instead:
$(document).ready(function() {
/* *** */
//Validating the input fields
$("[name=loginForm]").submit(function() {
var $username = $("#username").val(),
$password = $("#password").val();
/* *** */
});
});

Related

Form validation with java script

Trying to validate a form but I am facing constant problems. Here is the code
HTML:
<form id="regForm" class="form-group" method="POST" action="signup.php">
<div class="col-md-12">
<h2>Job Pocket</h2>
</div>
<div class="col-md-12">
<input placeholder="email" class="form-control"type="text" name="email" id="email">
</div>
<div class="col-md-12">
<input placeholder="password" class="form-control" type="password" name="password" id="password">
</div>
<div class="col-md-12">
<input placeholder="confirm password" class="form-control" type="password" name="confirmpass" id="confirmpass">
</div>
<div class="container">
<div class="row">
<div class="col-md-6">
<input placeholder="first name" class="form-control" type="text" name="first_name" id="first_name">
</div>
<div class="col-md-6">
<input placeholder="last name" class="form-control" type="text" name="last_name" id="last_name">
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" onclick="return validation()"class="btn btn-primary"name="submitsignup" id="submitsignup" value="submit">
</div>
<hr>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
<p id="mg"></p>
</div>
JavaScript:
<script type="text/javascript">
function validation(){
if(document.getElementById("email").value=="" || document.getElementById("password").value=="" || document.getElementById("last_name").value=="" || document.getElementById("first_name").value==""){
document.getElementById("mg").innerHTML="Fill all fields";
return false;
}
var emails = document.getElementById("email").value;
else if(emails.indexOf('#') <= 0){
document.getElementById('mg').innerHTML =" ** # Invalid Position";
return false;
}
else if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
document.getElementById('mg').innerHTML =" ** . Invalid Position";
return false;
}
else {
document.getElementById("regForm").submit();
}
}
</script>
The form keeps submitting itself. It works for the first if statement but after that it ignores the two else if and submits itself.
Even if I comment out this statement, it still submits to signup.php
document.getElementById("regForm").submit();
At the moment I have no idea why it is submitting so I am adding the php code aswell.
if(isset($_POST['submitsignup'])){
$date = array();
if($_POST['email']=='' || $_POST['password']=='' || $_POST['first_name']=='' || $_POST['last_name']==''){
$template->error="Please fill all fields";
}}
I added this bit of code in the signup.php file for an extra check but I have seen that it strightup submits to signup.php.
EDIT: Updated answer to updated question
Your problem might be related to the fact that you have this line of code:
var emails = document.getElementById("email").value;
before the elseif, which might break the if elseif flow.
Try using this code instead:
function validation(){
var emails = document.getElementById("email").value;
if(emails=="" || document.getElementById("password").value=="" || document.getElementById("last_name").value=="" || document.getElementById("first_name").value==""){
document.getElementById("mg").innerHTML="Fill all fields";
return false;
}
else if(emails.indexOf('#') <= 0){
document.getElementById('mg').innerHTML =" ** # Invalid Position";
return false;
}
else if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
document.getElementById('mg').innerHTML =" ** . Invalid Position";
return false;
}
else {
document.getElementById("regForm").submit();
}
}
Try with:
<input type="button"
instead:
type="submit"
Edit: otherwise your .submit() function is useless.
-2 ? Tell me why using .submit() if the form as already submit type ?

My JavaScript form validation function is called two times

I am trying to print the value from the form when a user submits the function but a blank value is returned.
Here is my JavaScript code:
var login = new function()
{
var name = null ;
this.validation = function()
{
this.name = document.getElementById("Username").value;
console.log(this.name);
document.getElementById("demo").innerHTML = this.name;
};
};
And my HTML form as :
<body>
<div class="container">
<div class="col-md-8">
<div class="starter-template">
<h1>Login with javascript</h1>
<p class="lead">Please Enter Following Details</p>
<h1 id="demo"></h1>
<form name="form" onSubmit="return login.validation();" action="#" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" name="username" class="form-control" id="Username" placeholder="Please Enter your Username">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="Email" placeholder="Please enter your Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="Password" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Re-Password</label>
<input type="password" class="form-control" id="Re-Password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
<script src="js/login.js"></script>
<script href="js/bootstrap.js"></script>
<!-- /.container -->
</body>
Why does the value not get into html <p> tag.
Your code simply works. But since the function executes on submitting the form, the username gets logged in the console fast before the page refreshed with submitted data. You can confirm this and test it by adding event.preventDefault(); to the function to prevent submitting the form so the page would stay visible with the console.
<script>
var login = new function()
{
var name = null ;
this.validation = function()
{
event.preventDefault();
this.name = document.getElementById("Username").value;
console.log(this.name);
document.getElementById("demo").innerHTML = this.name;
};
};
</script>
If that's not what you're looking for, let me know.
We the javascript validation failed you need to return false. If you don't it will proceed your form further. Thanks
var login = new function()
{
var name = null ;
this.validation = function()
{
this.name = document.getElementById("Username").value;
document.getElementById("demo").innerHTML = this.name;
return false;
};
};

Angular - $scope.myForm.$setPristine() is undefined

Form is not cleared after saved record in angularJs. I'm trying to reset form many ways, but form is not reset.
My angularjs version is 1.4.8.
This question is also a duplicate, but I tried what stack overflow users said. That has not worked for me.
Looking for a positive reply
Thank you.
Html code:
<form name="myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue"
id="forumValue" placeholder="fourm Id" />
<div class="form-group row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="answer" class="form-control"
ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success"
ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
Controller Code:
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};
Is your form wrapped in an ng-if statement? If so, the form might be inside a child scope, and you might try:
Option A
Replace your ng-if with an ng-hide.
Option B
Bind the form to an existing object on the parent scope:
$scope.myData = {};
$scope.saveUserAnswer = function(fid) {
...
};
Then in your HTML, refer to the form on the parent scope:
<form name="myData.myForm" id="myForm" novalidate>
</form>
Source: https://github.com/angular/angular.js/issues/15615
I have attempted to recreate your problem but without the call to the UserRepository just to confirm that we can set the form $pristine value to true and to reset the form.
<form name="form.myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue" id="forumValue" placeholder="fourm Id" />
<div class="form-grou`enter code here`p row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="form.myForm.answer" class="form-control" ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success" ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
<pre>{{form.myForm.$pristine}}</pre>
and the controller code like so :
$scope.form = {};
$scope.saveUserAnswer = function(fid) {
$scope.form.myForm.$setPristine();
$scope.fid = {};
//omitted the user repository code
};
The above will set the pristine value of the form to true and also reset the value of fid on click of the button.
EDIT
Also the call to your repository function should be in this format:
UserRepository.saveUserAnswer(fid).then(
function(response){
//success
},
function(response){
//error
}
);
In controller try to add '$scope.fid.answer=null;' after scope.myForm.$setPristine();
like this.
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.fid.answer=null;
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};

jQuery ajax second post

When I hit the submit button at the first time these codes works. But when I hit the second time to the button even if email and password values were true nothing happens and the user can not login. But if I write the true values at the first time, it works and user can login. So I figured the cause of this problem is about the "return false;" phrase. But if I remove return false; phrase, the form posts and ajax codes become useless. I must avoid the posting without ajax.
jQuery:
<script>
$(document).ready(function(){
$('#submit-btn').click(function(){
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if(email == "") {
$('#email').css({
"background-color": "#FF7070"
});
$('#box1').css({
"visibility": "visible"
});
return false;
}else if(password == "") {
$('#password').css({
"background-color": "#FF7070"
});
$('#box2').css({
"visibility": "visible"
});
return false;
}else{
$.ajax({
type: "POST",
url: "ajax.php",
data: $('#loginform').serialize(),
timeout: 5000,
success: function(c) {
if(c == "no") {
$('#box3').css({
"visibility": "visible"
});
return false;
} else if (c == "ok") {
window.location.href = "homepage.php";
}
},
error: function(a, b) {
if (b == "timeout") {
alert("Error: #101");
}
},
statusCode: {
404: function(){
alert("Error: #102")
}
}
});
}
return false;
})
});
</script>
Html:
<form name="loginform" id="loginform" method="post" action="">
<div class="field">
<input type="text" maxlength="40" id="email" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="password" id="password" name="password" placeholder="Password" autocomplete="off">
</div>
<div class="field">
<input type="submit" id="submit-btn" value="Log in">
</div>
<div class="keep-login">
<label for="remember">
<input type="checkbox" name="remember" id="remember" checked="checked">Remember me
</label>
<span>Forgot password?</span>
</div>
</form>
PHP:
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'email' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('email'), Input::get('password'), $remember);
if($login) {
echo "ok";
} else {
echo "no";
}
} else {
echo "no";
}
}
}
First, remove the method and action attributes of the form element. You can remove the form tag altogether but if you want to support non-javascript submissions, you'll need the form tag (however, the original question did not ask for this). You're 'submitting' the form via jQuery, so you don't need a method and an action on a form tag.
Input type="password" never autocompletes, so you don't need that attribute.
I also added an error div. Here is your new html:
<div id="error" style="display: none;">Login failed.</div>
<form>
<div class="field">
<input type="text" maxlength="40" id="email" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="password" id="password" name="password" placeholder="Password">
</div>
<div class="field">
<input type="submit" id="submit-btn" value="Log in">
</div>
<div class="keep-login">
<label for="remember">
<input type="checkbox" name="remember" id="remember" checked="checked">Remember me
</label>
<span>Forgot password?</span>
</div>
</form>
Replace your $.ajax statement with a $.post statement, and simply your logic.
$.post("ajax.php", { e: email, p: password }, function (data) {
if (data == "ok") window.location.href = "homepage.php";
else $("#error").slideDown().delay(3000).slideUp(); // I added div#error with "Failed to Login" message in the html above
});
This code will now redirect if the returned data is "ok"; otherwise, it will show div#error (again, this is in the html above), delay for 3 seconds, and then hide the message.
The return false; is unnecessary in each instance in your code above because after each conditional, the code ends - there is no other code to prevent from executing (which is why you would use return false; in this context).
You can do the $.trim on the same line as when you assign the variables, like I did with the slideUp, delay, and slideDown.

Implemented reCaptcha... Still getting spam

I just implemented a reCaptcha on a WP Site contact form.
It works like this:
Submission is cancelled using $form.submit(function(e) { e.preventDefault(); return false; }
reCaptcha is dynamically inserted before the form.
if reCaptcha's AJAX response is successful, perform HTLMFormElement.submit, using $form[0].submit();
HTML
<div id="ny_cf-3" class="footer-ny widget widget_ny_cf"><h2 class="widgettitle">Contact Us</h2>
<!-- contact form widget -->
<p class="response"></p>
<form method="post" enctype="multipart/form-data" class="ny-footer-contact-form" action="http://wpstage.leadscon.com/leadsconny/" data-submit="return fm_submit_onclick(1)" id="fm-form-1" name="fm-form-1">
<div class="form-group" id="fm-item-text-53546749dea0d">
<input type="text" name="text-53546749dea0d" id="text-53546749dea0d" style="width:px;" placeholder="Your name" class="form-control">
</div>
<div class="form-group" id="fm-item-text-5354674e4b90b">
<input type="text" name="text-5354674e4b90b" id="text-5354674e4b90b" style="width:px;" placeholder="Email address" class="form-control">
</div>
<div class="form-group" id="fm-item-textarea-5354675009293">
<textarea name="textarea-5354675009293" id="textarea-5354675009293" style="width:px;height:100px;" placeholder="Your message" class="form-control"></textarea>
</div>
<input type="email" class="teddybear" style="display:none">
<button type="submit" id="fm_form_submit" name="fm_form_submit" class="btn btn-primary btn-block submit">Submit</button>
<input type="hidden" name="fm_nonce" id="fm_nonce" value="1165f15ac2">
<input type="hidden" name="fm_id" id="fm_id" value="1">
<input type="hidden" name="fm_uniq_id" id="fm_uniq_id" value="fm-536b89c742833">
<input type="hidden" name="fm_parent_post_id" id="fm_parent_post_id" value="4">
</form>
<!-- end cf widget -->
</div>
JavaScript code:
var getRecaptcha = function($form, $frmResponseField) {
$form.fadeOut();
// Add the reCaptcha
// ========================================================================
var $recaptchaForm = $('<form class="recaptcha_form" style="display:none;"><p><strong>Spam verification (sorry):</strong></p><p class="response"></p><button class="btn btn-success btn-sm" type="submit">Submit</button></form>');
var recaptcha_el = $('<div id="recaptcha_el"></div>').insertAfter($recaptchaForm.find('.response')).get(0);
$recaptchaForm.insertBefore($form).slideDown();
leadsCon.reCaptchaHTML().appendTo($(recaptcha_el));
Recaptcha.create('6LdUZPASAAAAAGZI_z-qQ7988o0nGouHHtIsh4yX', recaptcha_el, {
theme : 'custom',
custom_theme_widget: 'recaptcha_widget',
callback: Recaptcha.focus_response_field
});
// Bind submit action to check it
$recaptchaForm.submit(function(e) {
e.preventDefault();
var challenge = Recaptcha.get_challenge();
var response = Recaptcha.get_response();
var $btn = $recaptchaForm.find('button[type="submit"]')
var btnVal = $btn.html();
var $responseField = $recaptchaForm.find('.response');
var data = {
action: 'verify_recaptcha',
challenge: challenge,
response: response
};
$btn.html("<i class='dashicons dashicons-clock'></i>");
$responseField.text('');
$.post(ajax_object.ajax_url, data, function(response) {
if ( response.success == true ) {
$responseField.removeClass('text-danger').addClass('text-success').html('<i class="icon-ok"></i> You got it. One second...');
// We're ok.. send.
Recaptcha.destroy();
$recaptchaForm.remove();
$frmResponseField.removeClass('text-danger').addClass('text-success').html('<i class="icon-ok"></i> Wait while we send your message.');
$form[0].submit();
} else {
$responseField.removeClass('text-success').addClass('text-danger').html('<i class="dashicons dashicons-dismiss"></i> Oops! Try again.');
$btn.html(btnVal);
}
});
});
};
$('.ny-footer-contact-form').submit(function (e) {
e.preventDefault();
var $form = $(this);
var $responseField = $form.siblings('.response').removeClass('text-success text-danger').html('');
var command = $form.attr('data-submit').match(/return (\w+)\((.+)\)/i);
var fn = window[command[1]];
var $honeypot = $form.find('input.teddybear');
if ( fn(command[2]) && $honeypot.val() == '' ) {
getRecaptcha($form, $responseField);
} else {
$responseField.removeClass('text-success').addClass('text-danger').html('<i class="dashicons dashicons-dismiss"></i> There are missing fields.');
}
return false;
});
My impression is that since $form[0].submit() is not in any way filtered and doesn't trigger the submit event from jQuery, spammers are using that to submit the form and circunvent the reCaptcha.
What can I do?
A spammer will not execute your javascript code. They will simply post to the correct URL. Therefore you can't reliably validate anything on the client, you'll have to validate it on the server as well.
Bots can even does not run your JS - they just find forms in raw html and try to act as an user submitting the form. You have to validate reCaptcha value on server side, see here: https://developers.google.com/recaptcha/docs/php

Categories