Submit button is not working after using javascript - php

I created a login page that has a login form which submits username and password to loginproc.php in order to check their validity and everything was working perfectly. Anyway, on the login page I wrote a JavaScript function that alert the user in case the username and password fields are empty. After I've done that, the JavaScript works fine but when i click the submit button nothing happens absolutely!
----------------------------------------This is the JavaScript----------------------
<script type='text/javascript'>
function formValidator(){
// Make quick references to our fields
var username = document.getElementById('username');
var password = document.getElementById('password');
// Check each input in the order that it appears in the form!
if(notEmpty(username, "The username field is empty!")){
if(notEmpty(password, "The password is empty!")){
}
}
return false;
}
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
</script>
----------------------------------------This is the form----------------------
<form method="post" action="loginproc.php" onsubmit="return formValidator()" >
<tr><td colspan="3"><img src="icons/login.jpg" alt="Edugate" width="366" height="123"></td></tr>
<tr><td colspan="3" nowrap bgcolor="#990033" class="infoTitle"><div align="center"></div></td></tr>
<tr><td colspan="3" nowrap class="infoTitle"><div align="left">user login </div></td></tr>
<tr><td colspan="3" nowrap bgcolor="#990033" class="infoTitle"><div align="center"></div></td></tr>
<tr><td width="58">Username</td>
<td width="4">:</td>
<td width="297"><input type="text" id="username" name="username" size="20"></td></tr>
<tr><td>Password</td><td>:</td><td><input type="password" id="password" name="password" size="20"></td></tr>
<tr><td> </td><td> </td><td><input type="submit" class="BtnInTable" value="Login"></td></tr>
<?php if ($error == 1)
print "<tr><td colspan='3' class='ppos'><img src='icons/error.png' alt='error'> Icorrect usename or password...</td></tr>";?>
<tr><td colspan="3" nowrap bgcolor="#990033" class="infoTitle"><div align="center"></div></td></tr>
</form>
Kindly, can anybody guide me. Thanks in advace

You forgot return true;, it will go to return false; otherwise.
// Check each input in the order that it appears in the form!
if(notEmpty(username, "The username field is empty!")){
if(notEmpty(password, "The password is empty!")){
return true;
}
}

You formValidator() always returns false, and if you return false to the onsubmit, it will not submit.
Be sure to return true if everything is valid.

heres the problem..
this function only returns FALSE.
no return true statement..
for form to submit, the "onsubmit" should return true :)

Related

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.

Form resubmits every time page is reloaded

Once the user signs in (in login.php) they are redirected to control.php. If they close the browser and reopen control.php they are asked to resubmit the form. How can I use the cookie I set up, instead of resubmitting the form?
login.php
<?php session_start(); /* Starts the session */
$logins = array('username' => 'pass12');
if(isset($_COOKIE['userME']) && isset($_COOKIE['passME'])){ //if cookie is set do this
$Username=$_COOKIE['userME'];
$Password=$_COOKIE['passME'];
echo $Username.'-'.$Password;
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
header("location:control.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>1Invalid Login Details</span>";
}
}
else{ //else new person
/* Check Login form submitted */
if(isset($_POST['Submit'])){
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
setcookie('userME',$Username,time()+60*60*24*10,'/','71.12.145.29');
setcookie('passME',$Password,time()+60*60*24*10,'/','71.12.145.29');
header("location:control.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>2Invalid Login Details:<?php echo $Username.'-'.$Password?></span>";
}
}
}
?>
<form action="" method="post" name="Login_Form">
<table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="Table">
<?php if(isset($msg)){?>
<tr>
<td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
</tr>
<?php } ?>
<tr>
<td colspan="2" align="left" valign="top"><h3>Login</h3></td>
</tr>
<tr>
<td align="right" valign="top">Username</td>
<td><input name="Username" type="text" class="Input"></td>
</tr>
<tr>
<td align="right">Password</td>
<td><input name="Password" type="password" class="Input"></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" type="submit" value="Login" class="Button3"></td>
</tr>
</table>
</form>
control.php
<?php
session_start();
echo "Hello, ".$_COOKIE['userME'].'<br>';
if(isset($_SESSION['UserData']['Username']))
{
if (isset($_POST['submit'])) {
switch ($_POST['submit']) {
case 'room_light':
//execute code here
break;
case 'blink':
echo shell_exec("sudo ruby /home/pi/Desktop/PiControl/blinkPin1.rb");
break;
}
}
?>
<form method="post">
<input type="submit" name="submit" value="room_light">
</form>
<?php
}
else
{
header("location:login.php");
}
?>
The usual way to deal with this is to actually create three web pages :
A form web page, that displays the form and on submission sends to page 2 ;
A checking web page, that checks the password, sets the cookie(s) and immediately redirects to page 3 ;
A result web page, that uses the cookie set by page 2.
Thus, when reloading page 3, it will immediately reuse the cookie set by page 2.
Besides, you should avoid storing the password in a cookie. You could at least store in the cookie hash('sha256', $password) ; and check against the (precomputed) hashes of passwords.
This way, the password never resides on disk and only in memory, which is better for security reasons. You can check out more information on this subject using the following links, courtesy of Fred -ii- : Is it secure to store passwords in cookies? ; php, is there a safe way to store password in cookies? ; Is it safe to store the password hash in a cookie and use it for “remember-me” login?
There would be even better hashing schemes, such as salting with a random values, but that would perhaps complicate too much for the application you're writing.

Empty a div and then load content into it automatically once user logs in

I want to use jQuery to empty a content div and load another page into that div once a user has logged in.
I use the normal way that works once a button is clicked:
$(document).ready(function() {
$("#login").click(function() {
$("#content").empty();
$("#content").load("DIS-loginform.php");
});
});
I don't want anything to be clicked to load another page in my content div.
This is the login script in my main page sidebar so it will output the username of the user once logged in,
<?php //LOGIN PHP SCRIPT
$login = $_POST['username'];
$loginpass =$_POST['password'];
if((isset($login)) || (isset($loginpass))){
include("DIS-connect.php");
$query = "SELECT * FROM user WHERE username='$login' and password=('$loginpass')";
$result = mysql_query($query) or die($query."<br/><br/>".mysql_error());
$count = mysql_num_rows($result);
//echo $count;
if($count >0){
echo "Logged in as <button id='user' value='$login'>$login</button>";
$_SESSION['valid_user'] = $login;
}
else{
echo "<p>sorry login failed</p>";
}
}
// LOGIN PHP END ?> `
And this is my simple login form that loads into the content div of my main page when the login option is selected.
<div id="login">
<form name="login" action="DIS-home.php" method="POST"
onSubmit="return confirm('Continue with Login?');">
<table border="1">
<tr>
<th>Username</th><td><input name="username" type="text" id="username" /></td>
</tr>
<tr>
<th>Password</th><td><input name="password" type="password" id="password" /></td>
</tr>
</table>
<input type="submit" name="Submit" value="Login" id="loginbutton" />
</form>
</div>
if you don't want anything to be clicked just use
$(document).ready(function() {
$("#content").empty();
$("#content").load("DIS-loginform.php");
});
instead of
$(document).ready(function() {
$("#login").click(function() {
$("#content").empty();
$("#content").load("DIS-loginform.php");
});
});
And I think you better change your SQL query because it's not save (SQL injections)! Also in the query: there is no hash or something on the password value? So maybe think about using an MD5 or SHA2 encryption?
And the last thing I see for the moment:
Instead of using:
if($count >0)
Use
if($count == 1)
This prevents hackers from logging in with an SQL injection that returns multiple rows.
For example:
I can login with using no password and this username:
' or 'test'='test' -- '
Because it would get a result with all your users and the password part in your query would be commented out.

Can't get php mailform submit button to refresh current DIV layer only

I can get the PHP mailform to work correctly. The problem is I would like the submit button upon validation to not refresh the entire page but just the content div layer. I have researched various solutions however I am fairly new to PHP so I may be entering the code incorrectly. The working page can be found at www.kaimeramedia.com/derek/Website and then by clicking on the contact link. The actual contact page code is:
<form method="post" id="captcha_form" name="form1" action="mailform.php">
<br />
<table width="100%" border="0">
<tr><td rowspan="4" width="125">
</td>
<td>
<div id="Imprint3">Name:</div></td>
<td width="15">
</td><td><div id="Imprint3">All fields are required.</div></td>
<tr>
<td width="150">
<input type="text" id="name" name="name" maxlength="30" value="name" onfocus="if
(this.value==this.defaultValue) this.value='';"/></td>
<td rowspan="5" colspan="2">
<table>
<tr><td width="10"></td><td>
<div id="Imprint3">Message:</div></td></tr>
<tr><td width="10">
</td>
<td width="200"><textarea name="message" id="message"
rows="6" cols="25" value="Enter your message" onfocus="if
(this.value==this.defaultValue) this.value='';"/><?php echo "</tex" . "tarea>"; ?>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input name="submit" type="submit" value="Submit" />
<input type="button" name="reset_form" value="Reset" onclick="this.form.reset();">
</td></tr></table>
</td>
</tr>
<tr>
<td valign="top"><div id="Imprint3">Email:</div></td> </tr>
<td valign="top">
<input type="text" id="email" name="email" maxlength="100" value="you#email.com"
onfocus="if(this.value==this.defaultValue) this.value='';"/></td>
</tr> <tr>
<td width="15"></td>
<td align="center"> <div style="padding-bottom: 1em;">
<img src="captcha.php" /> <br />
<input type="text" name="userpass" value="input the above text here" onfocus="if
(this.value==this.defaultValue) this.value='';"></div></td></tr></table></form>
and the mailform.php file is as follows:
<?PHP
session_start();
try{
$check = new check();
if(!isset($_REQUEST['email']))
throw new exception('You did not enter an email address.');
if(!isset($_REQUEST['message']))
throw new exception('You did not enter a message.');
if(!isset($_REQUEST['name']))
throw new exception('You did not enter a name');
$sender = $_REQUEST['email'];
$message = $_REQUEST['message'];
$name = $_REQUEST['name'];
$recipient = 'text#text.com';
$subject = 'Regarding Your Portfolio';
if($check->captcha('userpass') == FALSE)
throw new exception('Your captcha is incorrect.');
if($check->spam($sender) == FALSE)
throw new exception('Your email field contains spam.');
if($check->spam($name) == FALSE)
throw new exception('Your name field contains spam.');
if($check->length($sender, 10) == FALSE)
throw new exception('Your email field does not satisfy the minimum character
count.');
if($check->length($message, 8) == FALSE)
throw new exception('Your message field does not satisfy the minimum character
count.');
if($check->length($name, 3) == FALSE)
throw new exception('Your name field does not satisfy the minimum character count.');
mail($recipient, $subject, $message, "From: $name <$sender>" );
include'thankyou.php';
}catch (Exception $E){
die($E->getMessage());
}
class check{
function captcha($field){
if(isset($_REQUEST[$field])==FALSE){ return false; }
if($_SESSION['pass'] != $_REQUEST[$field]){ return false; }
return true;
}
function email($email){
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ return false;}
return true;
}
function spam($field){
if(eregi("to:",$field) || eregi("cc:",$field) || eregi("\r",$field) ||
eregi("\n",$field) || eregi("%0A",$field)){ return false; }
return true;
}
function length($field, $min){
if(strlen($field) < $min){ return false; }
return true;
}
}
?>
I have replaced my receiving email to text#text.com on this page, but on my site it is my actual email. Another user helped me a lot with getting this script functioning correctly, but I was wondering if it is possible to get the thankyou.php to refresh into the current div layer and not refresh the entire page. the line that I want to edit I believe is the: include 'thankyou.php'; Any help would be appreciated.
This is not possible with php.
You will have to use JavaScript to realize this.
You would be able to send the email without refreshing the page and to load a file in a div.
With e.g. jQuery and the $.ajax function it would look something like this:
var msg; // defines variable "msg"
$('#button_ID').click(function(e){
e.preventDefault(); // this prevents the page from reloading (or default behavior, so the form submit)
msg = $('#input_field_ID').val(); // gets the value of the input field and saves it in variable "msg"
$.ajax({
type: 'POST',
url: '/sendmail.php',
data: {message : msg}, // posts variable "msg" as "message"
cache: false,
success: function(data) {
$("#yourdivID").load('/thankyou.php'); // loads a file in a div
},
error: function(xhr, ajaxOptions, thrownError){
alert('there was an error');
}
});
});
In this example you would be able to get the message in sendmail.php with $_POST["message"]
Or use $.post and serialize your entire form:
$.post("/sendmail.php", $("#formID").serialize());
Just that you can see how to handle something like this.

loading a view twice in codeigniter

Hello I just started CodeIgniter. I am having problem in loading view.
My scenrio is I am creating a sample add form. After submit it goes to controller and insert entries in database. I want if the database operation is successfull it again comes to same view having again some values. And on the basis of those values I am showing some particular rows informing user about insertion operation. My function in controller looks like
public function add_user()
{
$this->load->view('add_user');
$post=$this->input->post();
if(isset($post['name']))
{
$data=array(
'name'=>$post['name'],
'designation'=>$post['designation']
);
if($this->db->insert('user',$data))
$result['update']=true;
else
$result['update']=false;
$this->load->view('add_user',$result);
}
}
And my view looks like
<h1 align="center">Add User</h1>
<table border="0" cellpadding="2" cellspacing="2" align="center">
<?php
if(isset($update))
{
if($update)
{
?>
<tr bgcolor="#00FF00">
<td>Record Added Successfully</td>
</tr>
<?php
}
else
{
?>
<tr bgcolor="#FF0000">
<td>Insertion Operation Failed</td>
</tr>
<?php
}
}
?>
<?php echo(form_open('first/add_user'));?>
<tr>
<td>Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Designation</td>
<td>
<select name="designation">
<option value="Junior PHP Developer">Junior PHP Developer</option>
<option value="Senior PHP Developer">Senior PHP Developer</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="Add User" />
</td>
</tr>
</form>
</table>
Now What I want that if insertion operation is successfull I am sending true value to view and if not I am sending false value. And on the basis of this value I am showing some rows. I am loading the view two times as per I understood the logic. Because first time it loads the form and second time It loads view with some value of true or false. But what happens that after it reloads there are two forms. I know this problem is due to double loading of my view. i want to ask if there is another way of sending values after database operation to view?
Simply load your view once:
public function add_user()
{
$post=$this->input->post();
$result = array();
if(isset($post['name']))
{
$data=array(
'name'=>$post['name'],
'designation'=>$post['designation']
);
if($this->db->insert('user',$data))
$result['update']=true;
else
$result['update']=false;
}
$this->load->view('add_user',$result);
}
By the way your code is a bit messy, work on it
// try something like this
//you may need to use form validation helper
//load add user form
public function add_user(){
//any data required for the form
$data['anything'] = '';
$this->load->view('add_user',$data);
}
//to process adding user action, form action will point to this
function adding_user(){
if($this->input->post('name')){
$data=array(
'name'=>$post['name'],
'designation'=>$post['designation'];
if($this->db->insert('user',$data)){
echo 'user added successfully!';
}else{
redirect(user/add_user);
}
);
}
}

Categories