JavaScript Not Working with HTML and PHP - javascript

I'm trying to create a simple registration form with basic HTML and PHP to insert data to my database. Basically, I want to validate the fields first before inserting the data and so I have created an external JavaScript file. Problem is, it is displaying the actual JavaScript code on the next page as opposed to validating!
My HTML file:
<html>
<head>
<title>Register Page</title>
<body>
<form id="register" method="POST" action="register.js" onsubmit="return verify()" action="register.php">
Forename: <input type="text" name="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
</body>
</head>
</html>
My JavaScript file:
<script type="text/javascript">
function verify(){
var forename = document.getElementById["forename"].value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
Instead of just validating I'm being redirected to a new webpage showing me the code I have written above.
I am completely new to web development and it would mean a lot if someone could help me out. All I want to do is just validate the fields before adding them to the database.

Two things you have to change
add id to your input control because you are fetching the value of text through Id
<input type="text" name="forename" id="forename">
syntax of getElementById()
var forename = document.getElementById("forename").value;
Once You do the validation for username and password. Submit the form
<script type="text/javascript">
function verify(){
var forename = document.getElementById("forename").value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
<form id="register" method="POST" onsubmit="return verify()" action="register.php">
Forename: <input type="text" id="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>

I think you should recheck your syntax for document.getElementById["forename"]
It should be document.getElementById("forename")
You can try debugging step wise. For example, try console.log.
var forename = document.getElementById("forename").value;
console.log(forename);
Try Chrome/Firebox Inspect element > Console and see if anything is been printed.
Hope this helps.
Peace! xD

You shouldn't be declaring register.js as the action for your <form>. The action attribute of a <form> element tells the browser where to send (POST or GET) the form data to, which is why you're being taken to register.js in your browser.
You need to intercept the browser submitting the form, do your validation, and then send the data on to your PHP file (register.php). It might be worth reading some tutorials on javascript form validation, such as this TutorialsPoint one.

What you can be able to do is to take your hole script into a echo in php, then create a php validation for the js and check if js got successfully done then execute script if so.

if you want your javascript on same html page then put this type
<html>
<head>
<title>Register Page</title>
<script type="text/javascript">
function verify(){
var forename = document.getElementById["forename"].value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
</head>
<body>
<form id="register" method="POST" action="" onsubmit="return verify()" action="register.php">
Forename: <input type="text" name="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
</body>
</html>

Related

Auto-fill specific login forms of a external webpage

I'm trying to pass credentials to fill automatically the inputs login of this website: https://www.pinterest.pt/login/ .
I don't know what are the variables. So I used the inspect of the browser to know what is the id of each input.
I'm using this code but it is not working:
function Test() {
var name = document.getElementById("id").value;
var password= document.getElementById("password").value;
document.forms["registerForm"].submit(); //form submission
}
<!DOCTYPE html>
<html>
<body>
<form id="registerForm" name="registerForm" method="post" target="_top" action="https://www.pinterest.pt/login/">
<input id="email" name="id" type="email" value="examplelogin" />
<input id="password" name="password" type="password" value="examplepassword" />
<input type="button" name="submit" id="btn" value="Submit" onclick="Test()" />
</form>
</body>
</html>
Do you know what I'm doing wrong?
Thank you for your help.
Not so much an answer to your question, but more of a future reference, you don't need to get all elements within a form via a selector. You can simply use the following technique:
function Test() {
let form = document.getElementById('registerForm');
var password = form.elements.password.value;
var email = form.elements.email.value;
form.submit();
}
Notice how accessing form.elements grants direct access to the element you're trying to read out.
I may just be nit-picking, but since this is a form submit, you probably need to use onsubmit and not just have the button click do something. Try this maybe?
<!DOCTYPE html>
<html>
<body>
<form id="formulario" name="formulario" method="post" target="_top" action="https://www.allianz.pt/area-privada" onsubmit="submitFunction()">
<input id="usuario" name="_58_login" type="text" value="examplelogin" />
<input id="password" name="_58_password" type="password" value="examplepassword" />
<button type="submit">Submit</button>
</form>
<script>
function Test() {
// your submit code
}
</script>
</body>
</html>
Forms can be very picky sometimes. Always best to use a working example for exactly what you're doing as a reference.

Html Form Unable to Validate Inputs using JavaScript

I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

JavaScript validation file not working: "ReferenceError: validateForm is not defined" (html linked)

(edit: code updated)
I am running into an error, when trying to clientside-validate with JavaScript that the user has filled in the forms correctly in the Register part of my HTML form.
The HTML and JS file are pretty straightforward:
(Fiddle)
JavaScript and HTML:
function validateForm() {
var name = document.getElementById('username').value;
var email = document.getElementById('email').value;
if (name == null || name == "" || checkIfSpaceOnly(name) == false) {
return false;
}
else if (email == null || email == "" || validateEmail(email) == false){
return false;
}
else
return true;
}
//other methods used in validateForm:
function checkIfSpaceOnly(input) {
var re = /\S/;
return re.test(input);
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
window.onload = function()
{
var submitBtn = document.getElementById('submit');
submitBtn.addEventListener("click", validateForm);
}
<!DOCTYPE html5>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="design.css">
</head>
<div class = "body1">
<div class = "forms" id="forms">
<h2>Log in</h2>
<form name='loginform' action='login.php' method='POST'>
<input type='email' name='email' placeholder="Email" ><br>
<input type='password' name='password' placeholder="Password" ><br><br>
<input type='submit' value='Log in'><br><br>
</form>
<hr>
<br><h2>Register</h2>
<form onsubmit="" name="register" action="register.php" method="POST" onsubmit="return validateForm()">
<input type="text" name="username" class="form-control" placeholder="Username" id="username"><br>
<input type="email" name="email" class="form-control" placeholder="Email" id="email"/><br>
<input type="password" name="password" class="form-control" placeholder="Passwoord"><br>
<br>
<input type="submit" name="submit" id="submit" value="Create user">
</form>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</html>
So the problem is, it's like the JS file isn't used at all by the HTML file. The form gladly registers any user, no matter if they fulfill the JavaScript file's if conditions or not.
I checked the console, and it says (when the user has been registered), "ReferenceError: validateForm is not defined".
Except checking that the file directories are correct of course, I have searched and read about both general HTML JS form validation Errors, 20-something "similar question" on here, and that specific ReferenceError. I've changed values, names, moved code parts around.... but I can't seem to find the problem and don't know what to do, although it feels like it's just a simple mistake somewhere in the code.
You have 3 problems
Your fiddle is setup incorrectly; all the code is wrapped in an onload which means your validateForm method is not accessible from HTML markup
You have 2 onsubmit attributes in the form - the second contains what it should contain but is being ignored because of the first
You assign the event handler both in markup and in code. Choose one, stick with it.
When you fix these 3 problems, it works as expected and does not submit the form if anything goes wrong (ie, false is returned from validateForm)
https://jsfiddle.net/spwx1rfd/7/
Please check the if condition, you have made a mistake.
Wrong code
if (uName == "") || checkIfSpaceOnly(uName) == false) {
return false;
}
Right code
if (uName == "" || checkIfSpaceOnly(uName) == false) {
return false;
}

js validation of not null field

I have done a login page. I want my js validateForm()function to alert a user if they have left out the username or password. This is the code I have got at the moment.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["username"].value;
if (x==null || x=="")
{
alert("Please enter username");
return false;
}
}
</script>
</head>
<div class="users form">
<br>
<form name="myform" action="Employees/login" onsubmit="return validateForm()" method="post" >
<?php
if (isset($error)) {
echo "<p style='color:red;font-size: 20px''>Username or Password is invalid. Please try again.</p>";
}?>
<p>Enter Username:
<input type="text" name="username" placeholder="username" style="height: 25px;width: 160px;"/></p>
<br><br>
<p>Enter Password:
<input type="password" name="password" placeholder="password" style="height: 25px;width: 160px;"/></p>
<br>
<input type="submit" style="height:35px;width:100px;font-size: 18px; align:center;" value="Sign in">
</form>
</div>
At the moment it is not working, and I think the problem is with the code line "var x=document.forms["myForm"]["username"].value;" Can someone please help?
The issue is forms["myForm"], you used an uppercase F, when actually your form name is all lowercase so it should be:
var x=document.forms["myform"]["username"].value;
// ^ lowercase
Not part of the problem, but you might prefer to use unobtrusive JavaScript to set the onsubmit handler instead of in the HTML attribute:
window.onload = function(){
document.forms["myform"].onsubmit = validateForm;
};
Now, in validateForm you can use this instead of finding the form manually.
function validateForm()
{
var x = this["username"].value;
...
}

Javascript for form validation isn't functioning

defined the script in the head of my html file but still doesn't function is it because the action for my form leads to a php file?
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["food_name"].value;
if (x==null || x=="")
{
alert("Food name must be filled out");
return false;
}
</script>
<title> my title is going here </title>
</head>
<body>
<form name="myForm" action="http://xxxxxxxxx/~xxxxxxxx/file/phpfile.php" method="post" onsubmit="validateForm()">
<b>foodName:</b> <input type="text" name="food_name"><br>
<b>Food Type:</b> <input type="text" name="food_type"><br>
<b>Total:</b> <input type="text" name="total"><br>
<b>Available:</b> <input type="text" name="available"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Fix the missing curly braces } for the validateForm function and update onsubmit to this
onsubmit="return validateForm()"
other wise it will submit the form even if validation is failed
check http://jsfiddle.net/Thu69/
you have missing brace in your validateForm function

Categories