eainnem eainnem - 6 months ago 18
HTML Question

Validating HTML form and using the $_GET in PHP method

I am trying to create a login where the user inputs their username and password and then on hitting the submit button the JavaScript code runs to validate that a string has been inputted. If the result is false, it should bring up

alert("...")
And if it is true it should continue with the submission.

However rather than bringing it to the linked php file when I go to validate the submission, it brings me to index.php (which is not the file I have linked it to) giving me a 404 Error saying the link is wrong or outdated and I can't see why or where I mis-linked it.

//// HTML ////



<html>
<head>

<script type="text/javascript">
function validateThis() {
var username = document.getElementById('username');
var password = document.getElementById('userpass');
if ((username.value =="") || (password.value == "")) {
alert("Please enter your details");
return false;
}

else {
return true;
}
}
</script>
</head>

<body>
<form id="myForm" name="myForm" action="loginValidate.php"
method="get" onSubmit="validateThis()">

<input type="text" name="username"/>
<input type="password" name="userpass"/>
<input type="submit" value="Login"/>

</form>

</body>
</html>


//// PHP ////



<?php

$username = $_GET ['username'];
echo "Hello".$username;

?>

Answer

You're checking the element by Id (getElementById) and should be using getElementsByName. You can also use document.forms['myForm'].username.value == "", i.e.:

<html>
<head>
<script type="text/javascript">
function validateThis(){
  if(document.forms['myForm'].username.value == "")
  {
    alert("empty");
    return false;
  }
    return true;
}
</script>  
</head>
<body>
    <form id="myForm" name="myForm" action="" 
    method="get" onSubmit="validateThis()">
    <input type="text" name="username"/>
    <input type="submit" value="Login"/>
    </form>
</body>
</html>
<?php
echo !empty($_GET['username']) ? "Hello ". $_GET['username'] : "";
?>  

PHPFIDDLE DEMO

Comments