Javascript doesn't run in PHP - javascript

I tried to look in other similar posts but apparently, I did something wrong somewhere without me noticing it as my PHP, HTML and JavaScript skills are very outdated. Last I touched these things was last year, so a lot of my fault detection skills are rusty.
That being said, the piece of code I'm trying to do is structured like this
<?PHP //If?>
JS //Script to check if input is empty and prevents submission
HTML <!--Input Forms-->
<?PHP //DB actions ?>
As far as I can do, the syntax of the PHP seems correct (used php formatter to check if my syntax is wrong). The problem here is the javascript portion does not even run. And if it runs, the remainder of the UI (login form) disappears for no reason (when input is supplied).
Below is the code I'm using.
<?php
if(empty($_POST["username"]) && empty($_POST["password"])){
?>
<script type="text/javacsript">
function checkField()
{
if((login-form.username.value == "") || (login-form.password.value == ""))
{
alert("Please fill in both Username and Password fields");
return false;
}
else
return true;
}
</script>
<div class="panel-body">
<form role="form" id="login-form" action="login.php" method="post" onsubmit="return checkField();">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" id="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" id="password" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<!--Login-->
<div class="form-group">
<button class="btn btn-lg btn-success btn-block" type="submit">Login</button>
</div>
</fieldset>
</form>
</div>
<?php
}else {
$message = "wrong answer";
echo "1<script type='text/javascript'>alert('$message');</script>";
}
?>
JavaScript for onsubmit is the main concern here. It does not even run when the supposed true condition is triggered (when either of the inputs are empty or both are empty). And the secondary script below, is just my initial test run before supplying the database portion.
Edit 1
Alt code for checkField() using getElementById
<script type="text/javacsript">
function checkField()
{
if((document.getElementById("username").value == "") || (document.getElementById("password").value == ""))
{
alert("Please fill in both Username and Password fields");
return false;
}
else
return true;
}
</script>
Edit 2
After resolving the typo, the PHP portion which is triggered when both login and password fields are not empty does not run at all. The action attribute might have a hand
<form role="form" id="login_form" action="" method="post" onsubmit="return checkField();">
The code above is to test if the action attribute is the culprit. Still the result is the same. The page will reload with empty fields.
Latest code
<?php
if(empty($_POST["username"]) && empty($_POST["password"])){
?>
<script type="text/javascript">
function checkField()
{
if((document.getElementById("username").value == "") || (document.getElementById("password").value == ""))
{
alert("Please fill in both Username and Password fields");
return false;
}
else
return true;
}
</script>
<div class="panel-body">
<form role="form" id="login_form" action="" method="post" onsubmit="return checkField();">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" id="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" id="password" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<!--Login-->
<div class="form-group">
<button class="btn btn-lg btn-success btn-block" type="submit">Login</button>
</div>
</fieldset>
</form>
</div>
<?php
}else {
$conn = mysqli_connect("localhost","root","rootacc","test");
if($conn)
{
echo "success";
header("LOCATION:tables.html");
}
}
?>
Edit 3
All problems resolved. Sorry for the newbie question, thank you for all who contributed. Here's the corrected code
<?php
if(empty($_POST["username"]) && empty($_POST["password"])){
?>
<script type="text/javascript">
function checkField()
{
if((document.getElementById("username").value == "") || (document.getElementById("password").value == ""))
{
alert("Please fill in both Username and Password fields");
return false;
}
else
return true;
}
</script>
<div class="panel-body">
<form role="form" id="login_form" action="" method="post" onsubmit="return checkField();">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" id="username" name="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" id="password" name="password" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<!--Login-->
<div class="form-group">
<button class="btn btn-lg btn-success btn-block" type="submit">Login</button>
</div>
</fieldset>
</form>
</div>
<?php
}else {
$conn = mysqli_connect("localhost","root","rootacc","test");
if($conn)
{
echo "success";
header("LOCATION:tables.html");
}
}
?>
Issue 1 is due to my own programming sloppiness (using dash instead of other styles of variable referencing) as well as the lack of knowledge on getElementById
Issue 2 is due to my own typo which wasn't spotted.
Issue 3 is due to the lack of understanding on id and name (seems the same)
All recommendation to fix the issues are implemented.

The post parameters are not set, that may be the reason it's not going to ELSE condition.
<div class="form-group">
<input class="form-control" placeholder="Username" id="username" name="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" id="password" name="password" type="password" value="">
</div>
Use, "name" attribute to set the POST parameters.

Related

How to return second register form on submition?

I have a page with two registration forms individual and business type and individual type form is set as default the other form is hidden, it works fine. but when I switch it to second form and click on submit button it submits second form but returns to first form after submition even on errors it return to first form.
I want it to stay on second form on errors and after submition.
Here is my php :
if (isset($_POST["btnRegister"])) {
echo "Done";
}elseif (isset($_POST["btnbusiness"])) {
echo "Done";
}
HTML and js codes in my page:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<div class="col-10 clmiddle">
<label for="production"><b>Individual</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development"><b> Business</b></label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</div>
First Form :
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second Form :
<div id="developmentSettings" style="display:none" class="col-12">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
EDIT: I changed JS to php, Here is the solution.
PHP codes (which get url):
$path = $_SERVER['REQUEST_URI'];
$Aurl = explode(",",$path);
for ($i=0; $i<count($Aurl);$i++){
$Burl = str_replace("?", "/", trim($Aurl[$i]));
}
$url = htmlspecialchars(basename($Burl));
$FormPostUrl = basename($path);
Html part :
Checkbox :
<div class="col-10 clmiddle" style="margin-top: 20px;">
<label for="production"><b>Individual</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php"); ?>" name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("register.php")){ echo 'checked="checked"';}?>>
<label for="development"><b>Business</b></label>
<input type="checkbox" value="<?php echo htmlspecialchars("register.php?business");?>"
name="checket"
onClick="if (this.checked) { window.location = this.value; }" <?php if($url === htmlspecialchars("business")){ echo 'checked="checked"';}?>>
</div>
First Form :
<?php if($url === htmlspecialchars("register.php")){?>
<div id="productionSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnRegister" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
Second form:
<?php } elseif($url === htmlspecialchars("business")){ ?>
<div id="developmentSettings" class="col-12">
<form action="<?php echo htmlspecialchars($FormPostUrl); ?>" method="post">
<div class="col-6">
<input type="text" class="form-control" name="fname" placeholder="Name..." required>
<button type="submit" name="btnbusiness" class="btn btn-primary right">Send</button>
</div>
</form>
</div>
<?php } ?>
You can use PHP to control whether display:none is added to your divs or not. Use an if statement (or a ternary operator might be neater syntax in the context) to make the decision about what to echo. Since the default is to display the production settings form, we only need to check whether the other form has been submitted or not, in order to know whether to change that.
e.g. something like this (untested):
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" <?php echo (isset($_POST["btnRegister"]) ? "" : 'checked="checked"'); ?> />
and
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" <?php echo (isset($_POST["btnRegister"]) ? 'checked="checked"' : ""); ?> />
and
<div id="productionSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "style='display:none'" : ""); ?>>
and
<div id="developmentSettings" class="col-12" <?php echo (isset($_POST["btnbusiness"]) ? "" : "style='display:none'"); ?>>
P.S. Unless you've massively simplified these forms for the purpose of your example, they appear to be basically identical. It's questionable whether you actually need two separate forms at all. The only difference appears to be the choice between "individual" and "business" - that could be handled by a single form with a radio button to choose the type, which would then simplify how you handle the postback as well, and reduce the amount of duplicated code and HTML. Of course if you're actually capturing more distinct fields for these forms than you've shown, then these remarks don't really apply.

Error message in contact form

I have created a contact (4 input text) form and I want if user doesn't text in anyone of input a text message will appear above each input.
Contact From:
<form class="form-horizontal" method="post" action="#" name="form" onsubmit="return validation();">
<fieldset>
<div><h2 style="font-family: Myriad Pro;color:#7f8c8c">form</h2></div>
<div class="form-group">
<div class="col-sm-8">
<input id="fname" name="name" type="text" placeholder="Όνομα" class="form-control">
<div id="error1" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input id="lname" name="surname" type="text" placeholder="Επώνυμο" class="form-control">
<div id="error2" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 ">
<input id="email" name="email" type="email" placeholder="E-mail" class="form-control">
<div id="error3" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 ">
<textarea id="message" name="message" type="text" placeholder="Το σχόλιο σας.." columns="7" rows="7" class="form-control" style="background-color:#e5e6e6;" required=""></textarea>
<div id="error4" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 text-center">
<button type="submit" class="btn btn-primary btn-block" id="label" >SEND</button>
</div>
</div>
</fieldset>
</form>
And the script I use:
function validation(){
if (document.form.name.value == "") {
document.getElementById('error1').innerHTML="*Error Msg1 ";
}else if (document.form.surname.value == "") {
document.getElementById('error2').innerHTML="*Error Msg2 ";
}else if (document.form.email.value == "") {
document.getElementById('error3').innerHTML="*Error Msg3 ";
}else if (document.form.message.value == "") {
document.getElementById('error4').innerHTML="*Error Msg4 ";
}
return false;
}
My issue is that if for example the user doesn't fill his name(error message displayed below the text field) BUT then if he text his name the error message IS still displayed.How can I solve this?
There is an example here: Fiddle
I would suggest that you clear the error message at the start of the validation again:
function validation(){
document.getElementById('error1').innerHTML=""
document.getElementById('error2').innerHTML=""
document.getElementById('error3').innerHTML=""
document.getElementById('error4').innerHTML=""
//Your validation code below:
...
}
This way whenever the input validates, all of the error messages will be cleared and evaluated again.
You might want to consider storing the labels at the start of the function in a field so you have easy access to them later. This should help with readability as well. For example:
function validation(){
var errorMessage1 = document.getElementById('error1');
//Access the label using your new variable:
errorMessage1.innerHTML = "Your value here"
...
On keyup event lets try resetting the error message
document.form.name.addEventListener("keyup", function(){
document.getElementById('error1').innerHTML = '';
});

Why is my form validation not working (onsubmit not triggering)?

I am writing a simple registration screen that allows a user to input their email address and password. As standard, I have the user inputting their email address and password twice to confirm. However, the onsubmit attribute on my form does not seem to be executing.
Here is the code:
Fields
<form name="form" id="form" action="" onsubmit="return validateForm()" class="form col-md-12 center-block" method="POST">
<div class="form-group">
<input type="text" class="form-control input-lg" name="name" id="name" placeholder="Full Name">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg" name="email" id="email" placeholder="Email Address">
</div>
<div class="form-group">
<input type="text" class="form-control input-lg" name="cemail" id="cemail" placeholder="Confirm Email Address">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" name="password" id="password" placeholder="Password">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" name="cpassword" id="cpassword" placeholder="Confirm Password">
</div>
<div class="form-group">
<button class="btn btn-primary btn-lg btn-block" form="form" type="submit" name="register" id="register">Register</button>
<span class="pull-right">Login</span><br>
</div>
</form>
JavaScript
<script>
function validateForm() {
if (isSame(document.getElementById("email"), document.getElementById("cemail"))
&& isSame(document.getElementById("password"), document.getElementById("cpassword"))) {
return true;
} else {
alert("Confirmation fields do not match, please retype and try again.");
return false;
}
function isSame(elementA, elementB) {
if (elementA.value.trim() == elementB.value.trim()) return true;
else return false;
}
//ignore this
function submitForm() {
document.getElementById("form").submit();
}
</script>
I have tried to debug as much as possible, but it doesn't seem like my submit button is triggering the form's onsubmit. I have viewed the request log, and it is posting the data just fine, however.
Thank you in advance!
The indentation of your code is incorrect: you are missing a } at the end of your validateForm function
There's a syntax error; there's no closing bracket for the first function.
Also, your isSame function doesn't need an if statement.
Hopefully this helps:
JS:
function validateForm() {
if(isSame(document.getElementById("email"), document.getElementById("cemail"))
&& isSame(document.getElementById("password"), document.getElementById("cpassword"))) {
return true;
}else{
alert("Confirmation fields do not match, please retype and try again.");
return false;
}
}
function isSame(elementA, elementB) {
return elementA.value.trim() == elementB.value.trim();
}

alert box in PHP and navigation to another page

I am using javascript to check whether username and password are not empty. If one of these is empty, javascript alert is displayed and PHP script should not work, that is username and password validation should not occur and login page should be displayed once again. Is there any simple code to do this?
Nobody need to build whole form. I have already build login form and PHP script for its validation, I just want to know is there any method or function in PHP to stop script on entering empty username/password and submitting
Try This
Php Code :
<p>
<label for="first">User Name:</label>
<input type="text" name="First Name" id="first" />
</p>
<p>
<label for="last">Password:</label>
<input type="text" name="Last Name" id="last" />
</p>
<input type="submit" name="Submit" id="button2" value="Submit" onClick="javascript:verify()"/>
JavaScript Code :
function verify() {
if (document.getElementById('first').value=="") {
alert("Please Enter Your Name");
return false;
}
else if (document.getElementById('last').value=="") {
alert("Please Enter Your Password");
return false;
}
else {
document.form.submit();
}
}
Working Model : http://jsfiddle.net/NWWL4/24/
It took me awhile to get this right. I have my form in my html index
page. On a closed question here, I read this couldn't be done.
This php works VERY well with my form.
It generates a Javascript alert for good and bad results and
links back to the index page in either instance.
If you look at the 2nd echo, you'll see where you can redirect to
another page. I just loaded same page to clear form.
If you want to see the ccs, just ask.
PHP:
<?php
if(isset($_POST['submit'])) {
$to = "admin#blahblah.com";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$subject_field = $_POST['subject'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field:\n Subject: $subject_field\n Message: $message\n";
}
if(empty($name_field) || empty($email_field) || empty($subject_field) || empty($message)) {
echo '<script type="text/javascript">alert("There is a problem, please check the fields");window.history.go(-1);</script>';
}
else {
if(mail($to, $subject_field, $body)) {
echo '<script type="text/javascript">alert("Message successfully sent");window.location = "https://www.blahblah.com/";</script>';
}}
exit;
?>
html:
<div class="clear"></div>
<div class="container">
<div class="row">
<div class="col-md-3">
<form role="form" action="php\mailer.php" method="post" id="form">
<div class="form-group">
<input name="name" type="text" class="form-control" id="name" placeholder="Your Name" maxlength="30">
</div>
<div class="form-group">
<input name="email" type="text" class="form-control" id="email" placeholder="Your Email" maxlength="30">
</div>
<div class="form-group">
<input name="subject" type="text" class="form-control" id="subject" placeholder="Your Subject" maxlength="40">
</div>
<div><input type="submit" name="submit" class="btn btn-primary" value="Send Message"></input></div>
</div>
<div class="col-md-9">
<div class="txtarea">
<textarea name="message" rows="10" class="form-control" id="message"></textarea>
</form>
<div class="clear"></div>
<div class="col-lg-12" style="text-align:center">
<a class="btn btn-large btn-contact-link" href="#blahblah_home">Home</a>

How to perform client-side form-validation on password

I am doing a simple sign-up page. For the password stuff, I need to check the new password and confirmed password are the same but no idea how
<div class="row">
<!--New Username-->
<div class="large-4 columns form-text">New Username</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="text" class="form-input" name="username" required>
</div>
</div>
<br/>
<div class="row">
<!--New email-->
<div class="large-4 columns form-text">Email</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="email" class="form-input" name="email" pattern="[a-zA-Z]*#[a-zA-Z]*" required>
</div>
</div>
<br/>
<div class="row">
<!--New Passwrord-->
<div class="large-4 columns form-text">New Password</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="password" class="form-input" name="password" required>
</div>
</div>
<br/>
<div class="row">
<!--Reconfirm new password-->
<div class="large-4 columns form-text">Re-enter Password</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="password" class="form-input" name="password-confirm" required>
</div>
</div>
That's quite a bit of code, but I broke out an example on a fiddle.
Simplified HTML:
<form id="passwordForm" action="#" method="POST">
Password:<br>
<input type="password" id="password"><br>
Confirm Password:<br>
<input type="password" id="confirmPassword"><br>
<input type="submit" id="submitButton" value="Check 'Em">
</form>
<div id="responseDiv"></div>
I used jQuery:
$(document).ready(function () {
$("#submitButton").click(function (e) {
e.preventDefault();
var matched,
password = $("#password").val(),
confirm = $("#confirmPassword").val();
matched = (password == confirm) ? true : false;
if(matched) {
//Submit line commented out for example. In production, remove the //
//$("#passwordForm").submit();
//Shows success message and prevents submission. In production, comment out the next 2 lines.
$("#responseDiv").html("Passwords Match");
return false;
}
else {
$("#responseDiv").html("Passwords don't match...");
return false;
}
});
});
Many times new learners will forget the e.preventDefault(); Without it, the form will submit regardless of any validation. Return false if there is something wrong, and the form will not submit.
There is an event listener on the submit button. If it is clicked, or the enter key is pressed will focused in the form, it will run the validation. If everything is fine, it will post the information to the URL in the action attribute of the form tag.
Another important point is to always re-validate on the server side. If a user has their Javascript turned off the form will post the information regardless of what is in your validation script.
with normal javascript, just adapt to your source code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function pass() {
var pass_1 = document.forms["myForm"].pass_1.value.length;
var pass_2 = document.forms["myForm"].pass_2.value.length;
if (pass_1 != pass_2) {
alert("the pass and repeat pass must be equal");
return false;
}
return true;
}
</script>
</head>
<body>
<form method="post" action="" name="myForm" onSubmit="pass(); return false;">
<input type="password" placeholder="type your pass" name="pass_1">
<input type="password" placeholder="confirm your pass" name="pass_2">
<input type="submit" value="validate">
</form>
</body>
</html>
the same code above but with the redirect: http://jsfiddle.net/m7BrM/
option 2 use a plugin:
http://www.technicalkeeda.com/jquery/password-and-confirm-password-validation-in-jquery

Categories