Javascript form validation doesn't execute - javascript

I have an input box. Upon submit, I have a PHP script which checks to see if the input box is empty. If it is, it displays an error message and runs a Javascript function.
My problem is that the error message appears, but the Javascript function doesn't execute.
Here's my script:
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
if(empty($username)) {
echo 'Please enter a username';
echo"
<script>
window.onload = function () {
function validate(e) {
var username = document.getElementById('username');
if (username.value.trim() == '') {
username.classList.add('error');
setTimeout(function() {
username.classList.remove('error');
}, 300);
e.preventDefault();
}
}
}
</script>
";
}else{
// something here
}
}
?>
<form method="post" id="login">
<input type="text" id="username" name="username">
<input type="submit" name="submit">
</form>

Where does your JavaScript function actually get executed? Removing the logic, the structure of what you have is:
window.onload = function () {
function validate(e) {
//...
}
}
So when the window loads, you execute a function. That function does nothing more than define another function. Nothing ever executes that other function.
If you want to execute that code when the window loads, don't wrap it in a function. Just execute it:
window.onload = function () {
// validation logic here
}

Related

Trying to run two functions on a form they both work independantly but cant get the both to work

in essence, I'm trying to validate a single field on a form to make sure it has content (Will eventually want to set a field length too) if the field validates then the second function should run. I've tried putting both functions in the action with && but that doesn't work - I've tried adding the field validation to an click on the button that works - but then doesn't run the next part
Any ideas?
<script type="text/javascript">
function OnSubmitForm()
{
if(document.ScriptFill.status[0].checked == true)
{
document.ScriptFill.action ="scriptcheck-complete.php?PUI=<?php echo $_GET["PUI"] ; ?>&STATUS=unfilled";
}
else
if(document.ScriptFill.status[1].checked == true)
{
document.ScriptFill.action ="scriptcheck-complete.php?PUI=<?php echo $_GET["PUI"] ; ?>&STATUS=filled";
}
else
if(document.ScriptFill.status[2].checked == true)
{
document.ScriptFill.action ="scriptcheck-complete.php?PUI=<?php echo $_GET["PUI"] ; ?>&STATUS=void";
}
return true;
}
</script>
<script type="text/javascript">
function validateForm() {
var x = document.forms["ScriptFill"]["Pharmacy"].value;
if (x == "") {
alert("You must enter your GPhC / RCVS number");
//return false;
}
}
</script>
Whate you can do is something like this in your javascript part:
<script type="text/javascript">
function OnSubmitForm()
{
/** Do what you want **/
document.getElementById('form').submit();
}
/** Considering this to be the first function you want to call **/
function validateForm() {
// Perform all the validations here
if(your validations pass){
/* Call your second function */
OnSubmitForm();
}
else{
return false;
}
}
</script>
Your HTML:
<form action='<your_action>' id='form'>
<input type='button' onclick='validateForm()' value='Submit'/>
</form>

JS form can't get it to submit

After validating my form with javascript I can not get it to submit to the server
myForm.addEventListener("submit", validation);
function validation(e) {
let data = {};
e.preventDefault();
errors.forEach(function(item) {
item.classList.add("cart__hide");
});
at the end of the validation I have the following code
if (!error) {
myForm.submit();
}
I also tried
if (error = false) {
myForm.submit();
}
if ((error == false)) {
myForm.submit();
}
when I console log error I am getting all false so the form should submit.
I am getting the following console log error
TypeError: myForm.submit is not a function
I did this same validation on an html page and it worked fine. Now I am trying to get it to work on a PHP page and it will not submit.
I am not sure why the myForm.submit() is causing the error.
Thanks
Jon
Remove e.preventDefault(); from your code and put it in your validation function like this:
if (error) {
e.preventDefault();
}
What you need to do is to only call Event#preventDefault when there is an error.
myForm.addEventListener("submit", validation);
function validation(e) {
var error = !form.checkValidity(); // replace this with the actual validation
if (error) e.preventDefault();
}
<form>
<input type="text">
<input type="submit" value="submit">
</form>

Submitting a form and run a function at the same time [duplicate]

This question already has answers here:
Form Submit Execute JavaScript Best Practice? [closed]
(3 answers)
Closed 11 months ago.
When I press the Submit button of a form it runs a php file which stores the answer to a db.
Is it possible to use the Submit button of a form to submit the user's choice and immediately after that run a function without further actions from the user?
For example, in the following simple form and php, how can I run a function when the user presses Submit?
<form action="db.php" method="post">
A:<input type="radio" name="answer" value="A">
B:<input type="radio" name="answer" value="B">
<input type="submit" name="submit value="submit">
</form>
<?php
$con = mysqli_connect('localhost','my user id','my password');
if(!con) {
echo 'not connected to server';
} else {
echo 'something else is wrong';
}
if(!mysqli_select_db($con,'my user id') {
echo 'Database error selection';
}
if (isset($_POST['submit'])) {
$answer=$_POST['answer'];
$sql = INSERT INTO test1 (columnName) VALUES ('$answer');
mysqli_query($con,$sql); // Execute query
}
?>
As an example let's take the following function which is a part of a larger file.
function next() {
var qElems = document.querySelectorAll('#questions>div');
for (var i = 0; i < qElems.length; i++) {
if (qElems[i].style.display != 'none') {
qElems[i].style.display = 'none';
if (i == qElems.length - 1) {
qElems[0].style.display = 'block';
} else {
qElems[i + 1].style.display = 'block';
}
break;
}
}
}
You can add an onsubmit event handler to the form
<form action="db.php" method="post" onsubmit="functionToCall()">
which will call the given function when the form is submitted. If you want to stop the form from being submitted, return false from the function. As #JokerDan said, you can also use AJAX within your function and omit the form action altogether.
function functionToCall() {
// Do something before you submit your form (save data locally or whatever)
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200) {
//Do something after submitting the form (if you want to change the page or redirect)
}
};
http.open('POST', 'db.php');
http.send(/*send post data here*/);
}
If you want to send data with the AJAX request, you will have to pull it from the form and put it in the http.send() line in the same format you pass data in the URL (data=answer&submit=true)
The proper way to do this, is to first select your form using something like document.querySelector or document.getElementById (only possible if the form element has an id).
var form = document.querySelector('[action="db.php"]');
After you selected your form, use the addEventListener of your form to add an evenListener.
form.addEventListener('submit', myListener, false);
Now you'll just need to create a function that looks like this :
function myListener(event) {
// DO STUFF
}
Here, event is an object of type Event that provides more information about the form you submitted. This function will be called every time you try to submit your form!

Autosave form on idleness

I have the below code that is supposed to autosubmit(save) a form with the name "project" when the user is idle. This is code I found on a tutorial website(forget the name), I tried it and it only refreshes the page?
<!-- Set auto save timeout in milliseconds
<script type="text/javascript">
attachEvent(window,'load',function(){
var idleSeconds = 5;
var idleTimer;
function resetTimer(){
clearTimeout(idleTimer);
idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
}
attachEvent(document.body,'mousemove',resetTimer);
attachEvent(document.body,'keydown',resetTimer);
attachEvent(document.body,'click',resetTimer);
resetTimer(); // Start the timer when the page loads
});
function whenUserIdle(){
document.project.submit();
window.location = location.href;
}
function attachEvent(obj,evt,fnc,useCapture){
if (obj.addEventListener){
obj.addEventListener(evt,fnc,!!useCapture);
return true;
} else if (obj.attachEvent){
return obj.attachEvent("on"+evt,fnc);
}
}
</script> -->
Form Code :
<form name="project" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="invoice-form" method="post" class="invoice-form" role="form" novalidate>
This is the code that is refreshing the page window.location = location.href; Try removing it.
And you also need to make sure your form's attribute name is replacing "project" in document.project.submit();.
For example
<form name="test_form"></form>
document.test_form.submit();
Edit:
Alright, the the function should just be
function whenUserIdle() {
document.project.submit();
}
Rather than doing an actual form submission, consider doing an AJAX request:
function whenUserIdle(){
var formData = {}; // assemble the form data here
$.post( "/form-submission-route", formData, function( responseData) {
// do something with result, if you like
// perhaps clear the form or throw up a notification
});
}

Validate form using jQuery

When a form submit button is clicked, a function to validate all the field is to be called. Nothing is to happen, however, if the validation fails.
I am using mailto: as my action, does this make a difference?
I would like to get clarification on two things:
Is this the correct way to call a function when clicking the submit button?
$(document).ready(function(){
$('#contactForm').submit(function(){
checkMail();
});
});
Can I still validate the fields even though I'm using mailto:?
Here is the rest of the code:
function checkEmail(){
var email = document.contact.email.value;
if(email == "") {
document.getElemtById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
HTML:
<form name="contact" action="mailto:exampleemail#hotmail.com" method="post">
<li>
<label for="email">Email</label>
<input id="email" type="text" name="email" placeholder="Enter Email Address">
</li>
<span id="email_error"></span>
Further, I don't get an error message on clicking submit.
No, you need the event handler to return false in case the validation failed. This will prevent the action from being executed, i.e. the mail program from being launched.
we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler.
Source
Modify it like this:
$(document).ready(function(){
$('#contactForm').submit(function(){
return validate();
});
});
Of course, this implies that the validate() function needs to actually return false in case the validation fails, and true otherwise.
Further you are missing id="contactForm" on your <form> tag.
Also, you need to grab the email value correctly:
var email = $("#email").val();
There's another mistake: You misspelled getElementById(). Here's a corrected version:
function checkEmail() {
var email = $("#email").val();
if (email == "") {
document.getElementById("email_error").innerHTML = "No Email Address";
return false;
}
else {
document.getElementById("email_error").innerHTML = ""
return true;
}
}
Or alternatively, using all jQuery:
function checkEmail() {
var email = $("#email").val();
var $error = $("#email_error");
if (email == "") {
$error.html("No Email Address");
return false;
}
else {
$error.html("");
return true;
}
}
Here's what you need:
$(document).ready(function(){
$('#contactForm').submit(function(){
if (!validate()) {
return false; // Prevent the submit
}
});
});
For validating the fields of your form, before sending it, you can use the jQuery's validation plugin:
$(document).ready(function(){
$("#contactForm").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button
// then:
$(form).submit();
}
});
});
Check the online doc for more information and examples: http://docs.jquery.com/Plugins/Validation#Validate_forms_like_you.27ve_never_been_validating_before.21

Categories

Resources