Problems With Dynamic Form Using JavaScript and PHP - php

I'm having trouble with these files, see if you guys can help me out :)
I get an object required error..
index.php
<?php
//Start session
session_start();
//Require functions.php
require("functions.php");
//Require posts.php
require("posts.php");
?>
<html>
<body>
<title>Log Into Booking System</title>
<?php
//Call function to display login
displayLogin();
?>
</body>
</html>
posts.php
<?php
if (isset($_POST['sublogin']))
{
//Check that all fields were typed in and are not null
if(!$_POST['user'] || !$_POST['pass'])
{
//Call function to display error
printText("Please make sure all required fields are filled in.");
}
else
{
//Here is some database checking
}
}
?>
functions.php
<?php
function displayLogin()
{
//Break php, then return to PHP
?>
<h1>Login</h1>
<form action="" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="3">
<tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr>
<tr><td><div id='error'></div></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="sublogin" value="Login"></td></tr>
</table>
</form>
<?
}
function printText($txtmsg)
{
?>
<!-- Set up the displayError javascript function -->
<script type="text/javascript">
function displayError()
{
document.getElementById('error').innerHTML = <?echo $txtmsg;?>;
}
</script>
<!-- Call function to Display the error -->
<script type="text/javascript">
displayError();
</script>
<?
}
?>
I'm pretty sure
document.getElementById('error').innerHTML
Is causing me problems, i think it might have to do with how im calling it, like it dosent know what its looking for..
Thanks guys much appreciated,
Jenny
EDIT: Here is the paste of what jQuerybeast tried to do, http://pastebin.com/jj0RVMAd
SOLUTION: Who knew it was this easy? You MUST change the order of where posts.php is required as well as make sure you don't call a javascript function within functions.php because that will execute the javascript above the form and therefore giving a null object error.
Index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Log Into Booking System</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<?php
//Start session
session_start();
//Require functions.php
require("functions.php");
?>
</head>
<body>
<?php
//Call function to display login
displayLogin();
//Require posts.php
require("posts.php");
?>
</body>
</html>
posts.php
<?php
//POST: Main login page
if (isset($_POST['sublogin']))
{
//Display error if feilds are not filled in
if(!$_POST['user'] || !$_POST['pass'])
{
echo '<script type="text/javascript">document.getElementById("error").innerHTML = "Please make sure all required fields are filled in.";</script>';
return false;
}
else
{
//Some database minipulation here....
//...
if ($_POST['user'] != $databaseUsername)
{
echo '<script type="text/javascript">document.getElementById("error").innerHTML = "Please make sure your username is correct.";</script>';
return false;
}
elseif($_POST['pass'] != $databasePassword)
{
echo '<script type="text/javascript">document.getElementById("error").innerHTML = "Please make sure your password is correct.";</script>';
return false;
}
}
return true;
}
?>
functions.php
<?php
//Function: Display main.php login
function displayLogin()
{
//Break php, then return to PHP
?>
<div style="float: left; padding: 10px; width:20%;">
<fieldset>
<legend>
<h1>Login</h1>
</legend>
<form name = "mainlogin" action="" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="3">
<tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr>
<tr><td colspan="2" align="left"><input type="checkbox" name="remember">
<font size="2">Remember username and password</td></tr>
<tr><td><div id="error"></div></tr><td>
<tr><td colspan="2" align="right"><input type="submit" name="sublogin" value="Login"></td></tr>
</table>
</form>
</fieldset>
</div>
<?php
}
?>

The first thing I notice is that the PHP-echoed string inside the Javascript function doesn't have quotation marks around it.
Change:
function displayError()
{
document.getElementById('error').innerHTML = <?echo $txtmsg;?>;
}
To:
function displayError()
{
document.getElementById('error').innerHTML = "<?echo $txtmsg;?>";
}

I think the problem is caused from functions.php is because you open and close PHP the opposite way.
Instead of ?> <?
Try: <? ?>
Which is this:
function displayLogin()
{
//Break php, then return to PHP
<?
<h1>Login</h1>
<form action="" method="post">
<table align="left" border="0" cellspacing="0" cellpadding="3">
<tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr>
<tr><td><div id='error'></div></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="sublogin" value="Login"></td></tr>
</table>
</form>
?>
}
function printText($txtmsg)
{
<?
<!-- Set up the displayError javascript function -->
<script type="text/javascript">
function displayError()
{
document.getElementById('error').innerHTML = <?echo $txtmsg;?>;
}
</script>
<!-- Call function to Display the error -->
<script type="text/javascript">
displayError();
</script>
?>
}

change
document.getElementById('error').innerHTML = <?echo $txtmsg;?>;
to
document.getElementById('error').innerHTML = '<?= $txtmsg; ?>';
or
document.getElementById('error').innerHTML = '<?php echo $txtmsg; ?>';

Use this
document.getElementById('error').innerHTML = '<?php echo $txtmsg; ?>';
and
It seems short tag is not enabled on your server. Please make sure.
Or always use <?php ?> instead of <? ?>

Related

Undefined index in uname and upass in php-why

I am new to PHP and i am trying to develop a small application in it. Received an undefined index error, tried to set the path right however could not overcome this error. It would be great if someone could help me solve this error. Please find the code attached below.
ERROR:Undefined index: uname in D:\wamp64\www\bbms\loginCheck.php
ERROR:Undefined index: upass in D:\wamp64\www\bbms\loginCheck.php on line 4
1.header.php
<html>
<body>
<frameset cols="20%,*">
<frame name="logo">
<img src="images/logo.jpg" width="20%" height="30%"/>
</frame>
<frame name="login">
<?php include('login.php');?>
</frame>
</body>
</html>
2.login.php
<html>
<head>
<script type="text/javascript" language="JavaScript">
function validate()
{
if(document.getElementByName("uname").value==""||document.getElementByName("upass").value=="")
{
document.getElementById("msg").innerHtml="Donor Login and password must not be left empty";
document.getElementByName("uname").focus();
document.getElementByName("upass").focus();
}
else
{
<?php header('Location:loginCheck.php');?>
}
}
</script>
<?php
if (isset($_GET['msg'])) {
$msg=$_GET['msg'];
}
else
$msg="";
?>
</head>
<body>
<p id="msg"><?php echo $msg;?></p>
<form method="post">
Donor Login<input type="text" name="uname" value="Enter your login id"><br>
Password<input type="password" name="upass" value="Enter the password"><br>
Forgot Password?<br>
<input type="submit" value="Login" onClick="validate()"/>
</form>
</body>
</html>
3.loginCheck.php
<?php
$uname=$_REQUEST["uname"];
$upass=$_REQUEST["upass"];
if($uname==""||$upass=="")
{
//echo "Must not be empty";
header('Location:header.php?msg=Donor Login and password must not be left empty');
}
else if($uname=="admin"&&$upass=="admin")
{
session_start();
echo "Welcome user";
}
else
{
header('Location:login.php?msg=Invalid Login');
}
?>
I think its not getElementByName it should be getElementsByName.
Please keep this source to cross check your syntaxes from next time.
Here is the link.
loginCheck.php should be the action of your form and not a redirect in the validate() function.
Try this way.
<html>
<head>
<script type="text/javascript" language="JavaScript">
function validate()
{
if(document.getElementByName("uname").value==""||document.getElementByName("upass").value=="")
{
document.getElementById("msg").innerHtml="Donor Login and password must not be left empty";
document.getElementByName("uname").focus();
document.getElementByName("upass").focus();
return false
}
return true
}
</script>
<?php
if (isset($_GET['msg'])) {
$msg=$_GET['msg'];
}
else
$msg="";
?>
</head>
<body>
<p id="msg"><?php echo $msg;?></p>
<form method="post" action="loginCheck.php" onsubmit="return validate()">
Donor Login<input type="text" name="uname" value="Enter your login id"><br>
Password<input type="password" name="upass" value="Enter the password"><br>
Forgot Password?<br>
<input type="submit" value="Login" onClick="validate()"/>
</form>
</body>
</html>

how to stop data automatically insert into database in php

I have problem in this code.
In this code when i press save data button , the data insert into database but when i refresh page then it's automatically insert into database, what should i do in my code then stop automatically insert data into database, thanks in advance
<?php
require './database/databaseConnection.php';
if(isset($_POST['save_button']))
{
if(($_POST['fname']&&($_POST['lname'])))
{
$first_name=$_POST['fname'];
$last_name=$_POST['lname'];
$qry="INSERT INTO user_master(first_name,last_name) values('$first_name','$last_name')";
$result= mysql_query($qry)or die(mysql_error());
if($result){
echo 'SuccessFully saved data';
}
else{
echo 'Data Not Inserted!';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="bootStrap/css/bootstrap.min.css">
<link rel="stylesheet" href="bootStrap/css/bootstrap.css">
</head>
<body>
<div class="container jumbotron ">
<form action="" method="post">
<table class="table-responsive">
<div class="form-group form-inline">
<tbody>
<tr>
<td> <label for="fname" class="label-info">First Name</label></td>
<td><input class="form-control" type="text" name="fname"></td>
<td><label for="lname" class="label-info">Last Name</label></td>
<td><input class="form-control" type="text" name="lname"></td>
</tr>
</tbody>
</div>
</table>
<button type="submit" name="save_button" class="btn-success" >Save Data</button>
</form>
</div>
</body>
</html>
This is happening because your action is empty
Update your action to this
action="<?php echo $_SERVER['PHP_SELF']; ?>"
Make a separate php file that will insert data to database. Give this in the form action attribute.
<form action="insert.php" method="post">
......
......
</form>
insert.php file
<?php
require './database/databaseConnection.php';
if(isset($_POST['save_button']))
{
if(($_POST['fname']&&($_POST['lname'])))
{
$first_name=$_POST['fname'];
$last_name=$_POST['lname'];
$qry="INSERT INTO user_master(first_name,last_name) values('$first_name','$last_name')";
$result= mysqli_query($qry)or die(mysql_error());
if($result){
echo 'SuccessFully saved data';
}
else{
echo 'Data Not Inserted!';
}
}
}
?>
You can use header() to redirect to your previous page if you want. Thus not allowing the refreshing of insert.php
header("location: your_page.php");
it will be safe if you use Prepared Statements
Take a look

showing div near save button if condition is true

I have simple code in php to enter name and address to the database.If name is already present in the database printing the message saying that it is already present ,if not entering data into database.But i want message has to be displayed near save button
<form method="POST" action="" >
<table>
<tr>
<td><br>Name t</td><td><br><input type="text" name="Name" id="wgtmsr" required/></td>
</tr>
<tr>
<td><br>Address</td>
<td><br/><textarea rows="3" cols="33" name="Address" id="inc_address" required></textarea></td>
</tr>
<tr>
<td><br></td><td><input type="submit" class="sav" name="rep" value="Save" id="btnsize" /></td>
</tr>
</table>
<?php
if (isset($_POST['rep']))
{
$Name=$_POST['Name'];
$Address=$_POST['Address'];
try{
$test=/* query check if name already present in database*/
if(!$test)
{
/*then insert into database*/
}else{
?> <div id="msg">
<?php echo "alreday present";?>
</div>
<?php
}
}catch(Exception $e) {
//echo "Error ".$e->getMessage();
}
}
But div is coming above the table.Please give suggestions so how can i style it near the save button
style:
#msg
{
color:#EA6262;
font-size:14pt;
margin-left:27% ;
margin-bttom:5% ;
}
Insert div after save button like
<input type="submit" class="sav" name="rep" value="Save" id="btnsize" /><span class="err" id="add_err"></span>
You can print the error using javascript.
document.getElementById("add_err").innerHTML = "Already having name!";
I tried similar thing its working
<?php
/**
* Created by PhpStorm.
* User: root
* Date: 3/9/15
* Time: 4:03 PM
*/
?>
<html>
<head>
<title></title>
</head>
<body>
<form>
<input type="submit" name="submit" /><span class="adderr" name="adderr" id="adderr"></span>
</form>
<?php
$var=0;
if($var==0)
{?>
<script>
document.getElementById("adderr").innerHTML = "Already having name!";
</script>
<?php
}
?>
</body>
</html>
It works fine

How to exit the application on 3 wrong attempts

I have made a login page where the No. of attempts is checked. The problem right now is it locks the user but keeps the counter for No. of Attempts increasing. I want to exit stop the counter to be increment. Please Help!
<html>
<head><title>Meeting Room Application</title>
<script type="text/javascript">
function validation()
{
var uname=document.forms["Login"]["txtuid"].value;
var pwd=document.forms["Login"]["txtpwd"].value;
if((uname==null || uname=="") && (pwd==null || pwd==""))
{
alert("Please fill all the details");
return false;
}
if(uname==null || uname=="")
{
alert("Please enter username");
return false;
}
if(pwd==null || pwd=="")
{
alert("Please enter password");
return false;
}
if(noofattempt>=3)
return false;
}
</script>
</head>
<body background="a6.jpg">
<?php
session_start();
if(isset($_SESSION['loginattempt']))
$NoOfAttempt=(int) $_SESSION['loginattempt'];
else
$NoOfAttempt=0;
?>
<table align="center" cellpadding="5" cellspacing="5">
<tr><td colspan="2" align="center"><img src="LOGO.jpg" width="275px;"> </td></tr>
<tr><th align="center" colspan="2">Kindly provide Login Details</th</tr>
<form method="post" name="Login" action="checkdb.php" onsubmit="return validation()" >
<tr><td align="right"><b>UserId : </td><td><input type="text" name="txtuid" placeholder="user"></td></tr>
<tr><td align="right"><b>Password : </td><td><input type="password" name="txtpwd" placeholder="*****"></td></tr>
<tr><td></td>
<td><font color="red">
<?php
if(isset($_SESSION['error']))
{
echo $_SESSION['error']."<br>";
echo "No Of Attempt ". $NoOfAttempt;
}
if($NoOfAttempt>=3)
echo "<br>Your Account Has been Locked..Contact Admin";
?> </font></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Sign in">
<input type="reset" value="Reset"><input type="hidden" name='NoOfAttempt' value= <?php echo $NoOfAttempt; ?> /></td>
</tr>
</form>
</div>
</div>
</table>
</body>
</html>
You are not retrieving the hidden form value NoOfAttempt in your validation() function.
var noofattempt=document.forms["Login"]["NoOfAttempt"].value;
Note that this will stop the user from accidentally submitting the form additional times after the limit has been reached, however as a previous commenter said, this can be easily overridden by someone who is trying to do so, or even possibly just by having Javascript disabled. So the limit should be enforced somewhere else in your PHP code.

my code is not working on action method

This code use for display report on front end and in csv file also displa this code running properly and this code is redirect on same page document.frmmonthly.action ="test2.php"; but second code is not working properly the code is not redirect to other page what is reason or what's the problem in my code......
document.frmmonthly.action ="csv.php";
action method is not working on csv.php.....my code is not working plz help me...
<head>
<script language="text/javascript">
function OnSubmitForm(value) {
if(value == 'Generate') {
document.frmmonthly.action ="test2.php";
} else if(value == 'Download') {
document.frmmonthly.action ="csv.php";
}
return true;
}
</script>
</head>
<form method="POST" onSubmit="return OnSubmitForm();">
</tr>
<tr>
<td><input type="submit" name="submit"
onSubmit="OnSubmitForm(this.value)"
value="Generate"></tr>
<tr>
<td><input type="submit" name="submit1"
onSubmit="OnSubmitForm(this.value)"
value="Download" action="csv.php">
</tr>
</form>
Try this:
<form method="POST" name="frmmonthly" onSubmit="return OnSubmitForm();">
[Edit:] Also you have to rename onSubmit e.g. to onClick
Try this
function OnSubmitForm(value)
{
if(value == 'Generate')
{
document.frmmonthly.action ="test2.php";
}
else if(value == 'Download')
{
document.frmmonthly.action ="csv.php";
}
return true;
}
</script>
</head>
<form method="POST" name="frmmonthly" onSubmit="return OnSubmitForm();">
</tr>
<tr>
<td><input type="submit" name="submit" onSubmit="OnSubmitForm(this.value)" value="Generate"></tr>
<tr>
<td><input type="submit" name="submit1" onSubmit="OnSubmitForm(this.value)" value="Download">
</tr>
</form>
I remove action=".." from input type
Ypu should name your form:
<form method="POST" onSubmit="return OnSubmitForm();" name="frmmonthly">
Since the form doesn't have a name, your method can't set it's action.

Categories