After onclick no error detect but cannot post into my database - javascript

this is my form name
<form name="form" id="form" method="post">
this my onclick
<input type="submit"
name="submit"
value="Register"
onclick="return validate()" />
this is my validate()
function validate()
{
var f = document.forms['form'];
var ary=[checkfname,checklname,checkEmail,checkAge,checkAdd,validtp,validhp,checkName,validpass];
var rtn=true;
var z0=0;
for (var z0=0;z0<ary.length;z0++)
{
if (!ary[z0](f))
{
rtn=false;
}
}
return rtn;
}
i think is my validate return there cannot return to post
hope someone can help me to solve the problem,thx...

Looks like you are storing an array of functions that make different validations:
var ary=[checkfname,checklname,checkEmail,checkAge,checkAdd,validtp,validhp,checkName,validpass];
Then you iterate that array and each function is executed receiving the form as parameter.
!ary[z0](f)
If you return false, the default action will be prevented, in this case the form won't be submitted.
So I'm pretty sure one of your validations is returning false. You should check each one of those functions and see wich one is returning false - you could debug using tools such as chrome dev tools or firebug.

Related

How to return a boolean in javascript to do form action

I have the following issue:
I have a foreach within a form, within this form I have a number type input that receives various data depending on the result of the query in the DB (normally they give results of 3 to 4 data) I have the code structured as follows :
<form autocomplete="off" action="somewhere.php" method="post" onsubmit="return validator();">
<?php
foreach($data["users"] as $dato){
$pco_user= $dato["pco_user"];
?> <p class="card-text"><strong><?php echo $pco_user; ?></strong></p>
<label>Number:</label>
<input type="number" name="votation[]" class="votation"></input><?php
}
?>
<button type="submit" id="submit3" name="button1" class="btn btn-secondary" value="Save" type="button">Save</button>
</form>
In the form tag I have the following code for onsubmit:
<script>
function validator()
{
const controls=document.querySelectorAll('.votation');
let ids=[];
controls.forEach(function(control)
{
event.preventDefault();
if(ids.includes(control.value))
{
alert('Duplicate values');
return true;
}
ids.push(control.value);
return false;
});
}
</script>
Basically what I am achieving at this moment is that the data that is being inserted is read before redirecting to the action of the form reading if there are equal values, but I cannot get that in the event that there are no equal values, I can redirect without problems, Any solution or can you tell me where I'm wrong?
You can prevent form submission by using event.preventDefault() but if the onsubmit function is assigned inline then the event must be passed to the function as a parameter.
You can use Array.every() to find duplicates as explained in this answer.
<form action="script.php" method="post" onsubmit="validator(event)">
<input type="number" class="votation">
<button type="submit">Save</button>
</form>
<script>
function validator(event) {
// get all control input values
const values = document.querySelectorAll('.votation').map(control => control.value);
// check if there are any duplicates
if (!values.every((element, index, array) => array.indexOf(element) === index) {
alert("Duplicate values found");
// prevent form submission
event.preventDefault();
}
}
</script>
Well, seeing your php HTML code you created a close tag for for <input>. HTML <input> tag does not have close tag.
Read more from this

calling a method if the validation function is true

When the submit button is pressed, my validation function should check if the fields are validated then call the setProfile method. currently when i click the submit button it will not validate my fields so something must be wrong
<form name="Login" method="post" action="#" onsubmit="return validateForm()">
<input type="text" name="fName" id="name"> <br>
</form>
<input type="submit" name="Update" value="Update">
function validateForm() {
var n = document.forms['Login']['fName'].value;
if(n==null || n=="")
{
alert("Please enter your name");
return false;
}
return true
}
function UpdateProfile() {
document.querySelector('submit').addEventListener('click', e=>{
const myProfile = new Profile
if (e.validateForm === true){
myProfile.setProfile();}
})
}
The most likely reason for your code not working is that your validateForm() function is not getting called at all on submit button press. To find out if that's the case, the simplest thing to do is to add an alert() at the top of the validateForm() function.
If it's indeed not called, google "call javascript function on button click" for a code sample. Here's one: Using an HTML button to call a JavaScript function

JavaScript: Why won't my form submit?

My problem is that my form, <form name="enrollment" method="post" action="submit.php"> will not submit. My submit button looks like: <input class="buttons" type="submit" name="submit" onclick="return validate()" value="Submit" />.
It calls this JavaScript function:
// Returns true if there are no errors and false if there are errors
function validate() {
// Something is not returning true here so that the form is not being submitted
if ( !window.err_exist ) {
// No errors
return true;
}
// There are errors
alert("Errors exist in the form!");
return false;
}
The variable window.err_exist is defined in the function getReviewValues(). In getReviewValues(), I set window.err_exist = false;. Then, I validate the form with conditionals of the form:
// Name
var r_string = "Name: ";
if ( document.forms["enrollment"]["name"].value.trim() == "" ) {
r_string += "<span class=\"error\">This is a required field!</span>";
window.err_exist = true;
} else {
r_string += document.forms["enrollment"]["name"].value;
}
Then, at the end of getReviewValues(), I return r_string; for dynamic feedback on the status of the form validations. That is, messages like "Name: This is a required field!".
Now, if I fill out my form but leave some things blank so that I have validation errors, I get the alert "Errors exist in the form!" and the form doesn't submit. Great! However, when I fill out my form so that I have no validation errors, I do not get the error message. Great! But, oh no! The form still doesn't submit. And it should!
So, since I'm not getting the error message, then the execution path must be in the conditional if ( !window.err_exist ). I can see this because function then returns true so that the function never gets to send out the message. But, if it returns true, then my form should submit. So it must be returning false, since the form is not submitting. But if it's returning false, then the execution path cannot be in the assumed conditional. If that were the case, then I would get the message but I do not get the message. This is a contradiction.
Anyone have any ideas?
Instead of an "onclick" handler on your submit button, use the "onsubmit" event on your form element. For example:
<form onsubmit="return validate()">
At this point, as long as your validate method is returning true or false correctly... it should behave how you expect.
See http://www.w3schools.com/jsref/event_form_onsubmit.asp for a better reference.
When you validation is a success (window.err_exist != false) the script returns true. Thus you are returning true for a click event not a submit.
This could be fixed by doing what jeltine says <form onsubmit="validate()"> or it could be fixed by replacing the
<input class="buttons" type="submit" name="submit" onclick="return validate()" value="Submit" />
with
<input class="buttons" type="button" name="submit" onclick="validate()" value="Submit" />
Then changing the validate function to call form.submit(); on no errors.
EXAMPLE:
//must add id to get element by id
<form name="enrollment" id="enrollment" method="post" action="submit.php">
function validate() {
// Something is not returning true here so that the form is not being submitted
if ( !window.err_exist ) {
// call submit on form
var myform = document.getElementById("enrollment");
myform.submit();
}
// There are errors
alert("Errors exist in the form!");
return false;
}
The advantage to doing it this way is that you have more control over changing form parameters such as action or method if needed. If these will not be needed then just change to onsubmit="".

Prevent action attribute from running php script with javascript [duplicate]

This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.

Stop a HTML5 form posting, refreshing or opening a new window onSubmit

I'm using the HTML5 form tag for the client side validator built into it, but I don't want it to submit a thing as I've just got a Javascript function to run instead.
How can i stop the Post method of the form.
Cheers - Caius
add a return false after the function call, like so:
<input .... onclick="function();return false;" />
or you could just return true/false from the function like so:
<input .... onclick="return function()" />
If you use jQuery you can do:
$('#your_form_id').submit(function(e){
e.preventDefault();
// do your staff
});
You can also do it without a framework:
document.getElementById('your_form_id').addEventListener('submit' function() {
// do your staff
return false;
});
In the "// do your staff" you can write your ajax code.
I tend to prefer leaving my functions as they are and add a return false to the onsubmit handler, ex:
<form onsubmit="aFunction(); return false;">
Add a onsubmit handler to your form, e.g.
<form method="POST" onsubmit="return sendForm();">
Then define the function and add false as return value:
function sendForm() {
//do your ajax request...
return false;
}
Add the onsubmit property to your form tag:
<form onsubmit="return myfunction()">
ensure you return a bool for your function
function myfunction() {
// do your validation
if (validation.passes) { // you will need to change this line !!!
return true; // to submit
} else {
return false; // to prevent submit
}
}
I've try all your solution but it still to reload the page after the ajax process :
<form id="form2" method="POST" onsubmit='sent(); return false;' >
function sent(){
$.ajax({
...
});
}

Categories