Ajax callback not executing - javascript

I have a form page that I intend submitting using Ajax. My plan is to
1. Check if email already exists using Ajax
2. Check if passwords match
3. If it does, switch to another "screen" and
4. Submit the form using Ajax
I'm confused because the validate function does not run. It neither switches screens not alerts when passwords do not match. As such, the form does not get submitted either. My code goes below
$('form input:last-child').click(function(e){
e.preventDefault();
var allFields = e.target.parentNode;
function validate () {
if (allFields.elements[3].value !== allFields.elements[4].value) {
return false; // If they don't match, return false
} else {
$('#form-div form').css('left', '-70%');
$('#confirm p').css('margin-left', '-12%'); // else switch screens
}
}
if (validate != false) {
$('#hidden').load("server_script.php"); // `hidden` is a hidden div somewhere on the page
} else
alert ("Passwords do not match");
});
I'm thinking, if they don't match, the rest of the event listener won't run since the false terminates the function from that point on. So I tried making an instance of the validate function outside the event listener and calling it inside the click function but it won't parse because of dependency variables so I'm not sure how to go about this.
UPDATE
Associated HTML attached. (Bonus: the regex pattern does not match 2 or more letters)
<div id=form-div>
<form method=POST action="" >
First Name: <br> <input type=text name=first_name pattern="[a-z]{2,}" required /> <br> <br>
Last Name: <br> <input type=text name=last_name pattern="[a-z]{2,}" required /> <br> <br>
Email: <span id=emailReport></span> <br> <input type=email name=email id=email required /> <br> <br>
Password: <br> <input type=password name=password required pattern=".{6,}" title="Password must be six or more characters" /> <br> <br>
Confirm password: <br> <input type=password name=password required /> <br> <br>
<input type=hidden name=sign_up_date />
<input type=submit value='sign up' />
</form>
<div id=confirm> <p>Some text</p> </div>
</div>
</div>

You forgot to call the 'validate' function.
As it seems by your code you just declared the function without executing him.

The validate function is not being called. Why not simply remove the function definition so the code is part of the click function?

You are not calling the validate function properly
Function calls must have the () i.e. validate() and not validate
$('form input:last-child').click(function(e){
e.preventDefault();
var allFields = e.target.parentNode;
function validate () {
if (allFields.elements[3].value !== allFields.elements[4].value) {
return false; // If they don't match, return false
} else {
$('#form-div form').css('left', '-70%');
$('#confirm p').css('margin-left', '-12%'); // else switch screens
}
}
//if (validate != false) {
if (validate() != false) {
$('#hidden').load("server_script.php"); // `hidden` is a hidden div somewhere on the page
} else
alert ("Passwords do not match");
});

Related

Javascript redirect to html

I've been trying to let javascript redirect to another html file using window.location but it keeps reloading. Here is the Javascript
var myStorage = window.localStorage;
let accounts = [{
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
}];
myStorage.setItem("account", accounts);
//check login account
var checkLogin = function() {
let uname = document.getElementById("Uname").value;
let pass = document.getElementById("Pass").value;
if (uname == "admin" && pass == "admin123!") {
myStorage.setItem("user", {
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
});
alert("Login admin");
window.location = "../account/myaccount.html";
alert("redirect");
} else {
myStorage.setItem("user", undefined);
document.getElementById("incorrectAccount").style.color = "red";
document.getElementById("incorrectAccount").innerHTML = "Incorrect Username or Password";
}
};
<form id="login" method="post" onsubmit="return checkLogin();">
<div>
<label><b>Username:
</b>
</label>
<input type="text" name="Uname" id="Uname" placeholder="admin"><br><br>
</div>
<div>
<label><b>Password: </b></label>
<input type="Password" name="Pass" id="Pass" placeholder="admin123!"><br><br>
</div>
<div>
<input type="submit" name="log" id="log" value="Log In"></a>
<span id="incorrectAccount"></span>
<br><br>
</div>
<div>
<input type="checkbox" id="check">
<span>Remember me</span>
</div>
<div>
Forgot Password?
<br><br>
Register
</div>
</form>
After typing the same username and the password, the first alert works and then it skips the redirect link and goes straight for the 2nd alert message
Submitting a form will cause the page to load the URL specified in the action attribute, which defaults to the current URL, which gives that effect though.
You must be trigging the JS when you submit the form. The JS runs, then the form submits, and the URL being navigated to changes.
You need to prevent the default behaviour of the form submission event.
e.g.
var checkLogin = function(event){
event.preventDefault();
and
document.querySelector('form').addEventListener('submit', checkLogin);
Re edit.
This is the problem. However, you are using event binding methods from before they introduced addEventListener (which became a standard in November 2000).
If you want to use intrinsic event attributes (I don't recommend them, they have some confusing gotchas) then you need to return false from the event handler.
onsubmit="return checkLogin();"
You are currently returning the return value of checkLogin, but that doesn't have a return statement so it returns undefined. You need to return false and not any falsy value.
function myRedirect() {
location.replace("https://stackoverflow.com")
}
<button onclick="myRedirect()">Replace document</button>

JS form validation to ensure that if a name is not entered a pop-up appears

The idea is that when the user is presented with the What is your name box, if they don't fill it in they would get a pop up message saying "please enter your name".
I don't understand why the form does not return the pop-up as I am calling the correct getElementsByName method I believe and checking if a value has been entered. I have tried changing the elementsByName to ("name") and ("UserInfo") but nothing happens. Does anyone have any ideas what might be the issue? I know the submit button is missing from the form but that was intentional as otherwise I'd have to post more code than necessary.
The code snippet is attached. The function name in html is called validate();
ALSO, I CANNOT MAKE ANY CHANGES TO THE HTML, IT NEEDS TO REMAIN AS IS.
function Validate() {
alert(document.getElementsByName("UserInfo")[0].value);
if (name == "" || name == null) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" />
</div>
</fieldset>
You are checking for name to be empty or null but the variable name isn't defined hence its always executing the else part.
Below is the working model of your snippet.
I had assigned the input value to value and check for existence, do alert if not a valid input.
function Validate(){
const value = document.getElementsByName("UserInfo")[0].value;
if(!value) {
alert('Please enter a name');
return false;
} else {
return true;
}
}
<h2>A Simple Quiz</h2>
<form onsubmit="Validate()">
<fieldset>
<legend>About You</legend>
<p id="UserInfo">What is your name?</p>
<div>
<input type="text" name="UserInfo" size="40" required />
<button type="submit">Submit</button>
</div>
</fieldset>
</form>
UPDATE:
Use required attribute.
Even better approach would be to wrap all the elements and submit button inside form and add required attribute to all required elements. Updated the answer.
Adding required will abort the submit itself.

Javascript form validation return false error

I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.

one of the two input fields is required

I have two input fields one is file the other is textarea
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
User has to either upload a file or type text. If the user leaves blank both of the inputs, it should say like "choose a file or type info" if he/she fills both, it is ok.
My JQuery:
$(function(){
$(".input_field").prop('required',true);
});
I have this code. How can we implement something like if else condition to make it required one of the fields?
See this fiddle https://jsfiddle.net/LEZ4r/652/
I modified your code to each all the elements with a class of input_field when the form is submitted.
$(function(){
$('form').submit(function (e) {
var failed = false;
$(".input_field").each(function() {
if (!$(this).val()) {
failed = true;
}
});
console.log(failed);
if (failed === true) {
e.preventDefault();
}
});
});
Based on your question, there are only two possible conditions:
if either one field or both fields are filled, user passes validation
if no fields are filled, user fails validation
This can be easily done by checking for the value of either input. As long as one is not empty, user passes the test. This if/else condition can be written as:
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
// Passed validation
} else {
// Failed validation
}
A simple pattern to check for errors is to create an error flag, which will be raised when one or more validation checks have failed. You evaluate this error flag at the end of the script before manual form submission:
$(function(){
$('form').on('submit', function(e) {
e.preventDefault();
// Perform validation
var error = false;
if($('input[type="file"].input_field').val() || $('textarea.input_field').val()) {
alert('Passed validation');
error = false;
} else {
alert('Please fill up one field');
error = true;
}
// Check error flag before submission
if(!error) $(this)[0].submit();
});
});
See working fiddle here: http://jsfiddle.net/teddyrised/LEZ4r/653/
Check inside your form If atleast one is done break the loop and go for submit else return false
$(function(){
$('form').on('submit',function(e){
var doneOnce = false;
$(this).children().each(function(){
if($(this).val()){
doneOnce = true;
return false;//return false will break the .each loop
}
});
alert(doneOnce)
if(!doneOnce){
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input class="input_field" type="file" name="title" />
<textarea class="input_field" name="info"></textarea>
<input type=submit />
</form>
You can write codes in Javascript to validate form. You have to make an onclick or onsubmit function, and the function will check whether any of the input field is empty. You can write something like the following code:
<script>
function validateForm() {
var fstname=document.getElementById("fname").value;
var lstname=document.getElementById("lname").value;
if(fstname===null || fstname===""){
alert("Plese choose a file.");
return false;
}
else if(lstname===null || lstname===""){
alert("Plese type file info.");
return false;
}
else{
return confirm("Your file: "+fstname+" and it of type "+lstname);
}
}
<body>
<form action="text.php" name="myForm" onsubmit="return validateForm()">
First Name: <input type="file" id="fname" name="FirstName">
Last Name: <input type=text" id="lname" name="LastName"><br/>
<input type="submit" value="Submit">
<form>
</body>

Check if html form values are empty using Javascript

I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:
Javascript:
function checkform()
{
if (document.getElementById("promotioncode").value == "")
{
// something is wrong
alert('There is a problem with the first field');
return false;
}
return true;
}
html:
<form id="orderForm" onSubmit="return checkform()">
<input name="promotioncode" id="promotioncode" type="text" />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Does anybody have an idea or a better solution?
Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:
Validate that every required input (within the form being submitted) is filled out.
Only provide the alert behavior if the browser doesn't already support the required attribute.
JavaScript :
function checkform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if(inputs[i].hasAttribute("required")){
if(inputs[i].value == ""){
// found an empty field that is required
alert("Please fill all required fields");
return false;
}
}
}
return true;
}
Be sure to add this to the checkform function, no need to check inputs that are not being submitted.
<form id="orderForm" onsubmit="return checkform(this)">
<input name="promotioncode" id="promotioncode" type="text" required />
<input name="price" id="price" type="text" value="€ 15,00" readonly="readonly"/>
<input class="submit" type="submit" value="Submit"/>
</form>
Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.
<input name="promotioncode" id="promotioncode" type="text" required />
Fiddle.
Demo: http://jsfiddle.net/techsin/tnJ7H/4/#
var form = document.getElementById('orderForm'),
inputs=[], ids= ['price','promotioncode'];
//findInputs
fi(form);
//main logic is here
form.onsubmit = function(e){
var c=true;
inputs.forEach(function(e){ if(!e.value) {c=false; return c;} });
if(!c) e.preventDefault();
};
//findInputs function
function fi(x){
var f = x.children,l=f.length;
while (l) {
ids.forEach(function(i){if(f[l-1].id == i) inputs.push(f[l-1]); });
l--;
}
}
Explanation:
To stop submit process you use event.preventDefault. Event is the parameter that gets passed to the function onsubmit event. It could be in html or addeventlistner.
To begin submit you have to stop prevent default from executing.
You can break forEach loop by retuning false only. Not using break; as with normal loops..
i have put id array where you can put names of elements that this forum would check if they are empty or not.
find input method simply goes over the child elements of form element and see if their id has been metnioned in id array. if it's then it adds that element to inputs which is later checked if there is a value in it before submitting. And if there isn't it calls prevent default.

Categories