a link in my codeigniter website only works on reload - javascript

I am developing a website on Codeigniter Framework i am facing an issue while making forgot password feature.
When i submit my email address it sends an email to that address and that email has a link that has a token in it. eg:
http://www.myegsite.com/user/forgotyourpassword/2991c14654e1ed41aab1565dcf815b0f
On click that link, if that token is not expired then, website asks for your new password and confirm password.
The issue is : When i provide new password and confirm password and click submit button it gives me following error:
An Error Was Encountered
The action you have requested is not allowed.
After reloading that same link, the page i get works absolutely fine, it updates my password again.
What could be the reason that link doesn't work first time?
Controller:
public function forgotyourpassword($token)
{
if($this->session->userdata('user_data') != NULL)
{
redirect(base_url() . 'User');
}else
{
//check if token exist in table or not , if not exist return false;
$this->load->model("data_access/extradataaccess","ExtraDataAccess");
$dbToken =$this->ExtraDataAccess->getToken($token);
if($dbToken == FALSE)
{
$this->session->set_flashdata("invalid_token",'This token is invalid!');
redirect(base_url() . 'welcome/forgotPassword');
}
else
{
//check if current date is smaller than expiry data , it means token is still valid return true;
if($this->ExtraDataAccess->GetTokenInfo($token) == FALSE)
{
//set flash data session for token expired
redirect(base_url() . 'welcome/forgotPassword');
//if token is expired return false
} //if ($currDate <= $expiryDate)
else
{
// load form libraries
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword', 'Password Confirmation', 'required|min_length[6]|max_length[20]|matches[password]');
if($this->form_validation->run() == FALSE)
{
$this->data['page_name'] = "Renew Password";
$this->data['form_url'] = base_url()."user/forgotyourpassword/";
$this->data['token'] = "$token";
$this->load->view("welcome/renewpassword_view",$this->data);
}
else
{
$tokenEmail = $this->ExtraDataAccess->GetTokenInfo($token)['email'];
$hashPassword = md5($this->input->post('password'));
//updating password into the database
$updateData = array (
'password' => $hashPassword
);
$this->db->where('email',$tokenEmail);
$this->db->update('users',$updateData);
}
}//else
}
}//if($this->session->userdata('user_data') != NULL)
}//Forgotyourpassword()
View:
<?php echo form_open("$form_url"."$token"); ?>
<div class="form-group">
<label for="inputpass">Password</label>
<input type="password" name="password" class="form-control" id="inputpass" value="" php echo placeholder="new password"/>
</div>
<?php if(form_error('password')!=NULL){
echo "<div id='fielderror'>";
echo form_error('password');
echo "</div>";
}?>
<div class="form-group">
<label for="inputpassconf">Confirm Password</label>
<input type="password" name="confpassword" class="form-control" id="inputpassconf" value="" placeholder="confirm password"/>
</div>
<?php if(form_error('confpassword')!=NULL){
echo "<div id='fielderror'>";
echo form_error('confpassword');
echo "</div>";
}?>
<h5><input type="submit" value="Reset Password" class="btn btn-info active"/></h5>
<?php echo form_close();?>

Related

problem with sending ajax form data to php

i cant send a form data with ajax to php. It always refresh the page. Im using bootstrap modal to register form and i want to display error message (if have) on the top of form. Always refresh the page and if i again click to reg button to open the modal i see the error message. How i can do it without refresh the page? Any idea how can i do it?
form:
<?php echo display_error(); ?>
<form id="regform" class="form-signin" action="#" method="post">
<input type="text" id="username" class="form-control" placeholder="username" name="username" required autofocus>
<input type="email" id="email" class="form-control" placeholder="email" name="email"required autofocus>
<input type="password" id="pass1" class="form-control" placeholder="password" name="password_1" required>
<input type="password" id="pass2" class="form-control" placeholder="password again" name="password_2" required>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" name="register_btn">Register</button>
</form>
js ajax
$('#register_btn').click(function(){
var data = {};
data.username = $('#username').val();
data.email = $('#email').val();
data.password_1 = $('#pass1').val();
data.password_2 = $('#pass2').val();
$.ajax({
type: "POST",
url: "functions.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
functions.php
include 'db_config.php';
session_start();
// connect to database
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
// REGISTER USER
function register(){
global $db, $errors;
// receive all input values from the form
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created!!";
header('location: home.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
The JQuery selector you are using is using an ID, change the button from name="register_btn" to id="register_btn".
EDIT: Further looking at your code, you are missing the prevent default on the button, I would change the listener to the form instead and prevent default. The form is submitting to the current page which is the default behavior, which is why it looks like the page is just reloading.
See the below link for my code I use for form posts via AJAX:
http://aspintech.ca/journal/?entry_id=77

Login with POST Form, which trigger a javascript validation, and AJAX to a PHP file. Trouble storing data to PHP

Brief
I am now stuck at a part of AJAX, as I do now know how to extract the data out from the AJAX part and put into the PHP variables, so that I could access it and use it later. It also does not redirect me to another page ("Map.php").
I tried looking online for the answers, but to no avail. Can anyone with experience please help. Also, I am not sure if my method of doing is correct, please let me know where I have done wrong.
In details
I want to do a "Login.php", which will use a form to take the email and password from the user. There will be a "Login" button on the form which will trigger a javascript for the purpose of validation.
Upon validation, I will use AJAX to call another php file called "Auth.php", which will have make a connection with a MySQL database, to search for that particular user verify the user.
The "Auth.php" will then return a json data of the user's particulars, which I intend to use in "Login.php" page, and to start a session with the $_SESSION[] variable of php. I also want the page to redirect the user to another page ("Map.php") upon successful login.
Below are parts of my codes in the "Login.php" and "Auth.php".
Login.php
<form name="myForm" action="Map.php" method="post" onsubmit="return validateForm()">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email" type="email" autofocus value="<?php echo isset($_POST["email"])? $_POST["email"]: ""; ?>">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="<?php echo isset($_POST["password"])? $_POST["password"]: ""; ?>">
</div>
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block"/>
</fieldset>
</form>
<script>
function validateForm() {
//event.preventDefault();
var email = document.forms["myForm"]["email"].value;
var password = document.forms["myForm"]["password"].value;
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,}))$/;
if (email == null || email == "") {
alert("Email must be filled.");
return false;
}
if (password == null || password == "") {
alert("Password must be filled.");
return false;
}
if(re.test(email)) {
var data = {
"email": email,
"password": password
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "GET",
dataType: "json",
url: "auth.php",
data: data,
success: function(data) {
alert("You have successfully logged in!");
// TODO store user details in session
return true; // return true to form, so will proceed to "Map.php"
}
});
return false;
}
else {
alert("You have entered an invalid email address!");
return false;
}
return false;
}
</script>
Auth.php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid=true;
if (isset($_GET['email']) && isset($_GET['password'])) {
$email = addslashes($_GET['email']);
$password = addslashes($_GET['password']);
} else {
$valid = false;
$arr=array('success'=>0,'message'=>"No username or password!");
echo json_encode($arr);
}
if($valid == true){
$query = "SELECT * FROM user WHERE email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Login failed");
echo json_encode($arr);
}
}
// close the connection that was established with MySQL for the SQL Query
mysqli_close($connection);
Your ajax call should be like this:
data = $(this).serialize() + "&" + $.param(data)
$.post('auth.php', data, function(response){
console.log(response);
});
you must use post method because you are getting password and email so its not a good practice. And for validation there is many jQuery plugins.

how to link php, sql, and Javascript together,

I'm doing a log in page, i have javascript doing validations ( checking if field is blank) sql storing the data and php doing what php does (idk).... anyway when I press submit it tells me Cannot POST /login.php
is there away to test it on a website and see if it actually works or is the code completely wrong.
<?php
$server = 'localhost';
$username = 'root';
$passowrd = 'cosc_453';
$dbname = 'login'
if(!empty($_POST['user']))
{ $query = mysql_query("SELECT * FROM UserName where userName ='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
{ $_SESSION['userName'] = $row['pass']; echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
else { echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{ SignIn();
} ?>
php external
function validate(){
if ( document.getElementById (user).value=="")
{
alert ("Please enter your user name");
}
else if ( document.getElementById(pass).value=="")
alert("Please enter you password");
else {
alert("Processing Login........");
}
}
javscript external
CREATE TABLE UserName (
UserNameID int(9) NOT NULL auto_increment,
userName VARCHAR(40) NOT NULL,
pass VARCHAR(40) NOT NULL,
PRIMARY KEY(UserNameID) );
INSERT INTO
UserName (userName, pass)
VALUES
("cosc" , "453");
sql external
<!DOCTYPE HTML>
<html>
<head>
<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="home.css">
<script src ="login.js"></script>
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="Post" action="login.php" submit =" validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
< /fieldset>
</div>
</body>
</html>
Your mysql do not have a connection to database. And please stop using mysql, use mysqli instead
<?php
$con = mysqli_connect("localhost","root","cosc_453","login");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM UserName WHERE userName ='".$_POST[user]."' AND pass = '".$_POST[pass]."'";
$result = mysqli_query($conn,$sql);
$count_result = mysqli_num_rows($result);
// Login Success URL
if($count_result == 1)
{
// If you validate the user you may set the user cookies/sessions here
#setcookie("logged_in", "user_id");
#$_SESSION["logged_user"] = "user_id";
$_SESSION["secret_id"] = $row['secret_id'];
if($row['level'] == 1)
{
// Set the redirect url after successful login for admin
$resp['redirect_url'] = 'admin/';
}
else if($row['level'] == 2)
{
// Set the redirect url after successful login for user
$resp['redirect_url'] = 'user/';
}
}
else
{
echo "Invalid username or pass";
}
?>
To add onto what Eh Ezani stated, you have an issue in your HTML. Your form attribute reads submit when I believe what you meant is onsubmit. Might want to try something like.
<form method="Post" action="login.php" onsubmit ="return validate()">
User:<br><input type="text" name="user" size="40"><br>
Password:<br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
Also, "Use MySQLi over the older MySQL functions. The "i" stands for "improved". The list of improvements can be found in the docs.
-credited to
Difference between mysqli and mysql?

<div> tag not showing JSON response with Ajax

I have made a simple login form which I am trying to validate through AJAX call. It works successfully. But problem is when I enter correct email or password it refreshes the whole page instead of showing JSON success-error to be shown in div and same for the wrong email/password. Any suggestions please!!
Code
<script>
$(document).ready(function() {
$('#login_submit').click(function(){
var email = $("#email").val(),
password = $("#password").val();
var proceed = true;
if(proceed){
post_data= { 'Email': email, 'Password': password};
$.post('login_index.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output=$('.alert-error').html(response.text);
}else{
output=$('.alert-success').html(response.text);
}
$("#error").hide().html(output).slideDown();
}, 'json');
}
});
});
</script>
<div class="alert-error"></div>
<div class="alert-success"></div>
<div class="login">
<form method="post" action="">
<input type="email" name="email" id="email" placeholder="email" >
<input type="password" name="password" id="password" placeholder="password">
<input type="submit" name="login_submit" id="login_submit" value="login">
</form>
</div>
Php
<?php
include "db/db.php";
session_start();
if($_POST){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(isset($_POST['Email']) && isset($_POST['Password']))
{
$email=filter_var($_POST["Email"], FILTER_SANITIZE_STRING);
$pwd=filter_var($_POST["Password"], FILTER_SANITIZE_STRING);
$query=mysqli_query($con,"select * from customers where email='$email' and password='$pwd'");
$count=mysqli_num_rows($query);
$row=mysqli_fetch_array($query,MYSQLI_ASSOC);
if($row)
{
$_SESSION['login_email']=$row['email'];
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$email .' You are successfully login'));
die($output);
}
else{
$output = json_encode(array('type'=>'error', 'text' => 'Could not login! Please check your email password.'));
die($output);
}
}
}
Prevent the default action of form or submit button using e.preventDefault() or else it will post the form and page refresh happens.
$('#login_submit').click(function(e){
e.preventDefault(); //e is the event captured here
//rest of the code
});
You can directly use return false, which will prevent default action and also propagation event.
$('#login_submit').on('click',function(){
//Complete code here
return false;
});

PHP login script doesn't work in IE8 or IE9

I have a site using a PHP script to login the user. It works fine in most browsers, but IE8 and IE9 seem to be having trouble with the cookies. I've read a bunch of similar posts, but so far nothing seems to help. Any ideas as to where the problem is here? Details are code are below.
We are using this code for our login script: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Login Form
<?php
if($error == 1) echo "<p class=\"error\">Your Log in information is incorrect</p>";
?>
<form class="form-horizontal" role="form" action="includes/process_login.php" method="post" name="login_form">
<div class="form-group">
<!-- <label for="inputEmail1" class="col-md-2 control-label">Email</label> -->
<div class="col-md-12">
<input type="email" class="form-control" id="inputEmail1" name="inputEmail1">
</div>
</div>
<div class="form-group">
<!-- <label for="inputPass1" class="col-md-2 control-label">Password</label> -->
<div class="col-md-12">
<input type="password" class="form-control" id="inputPass1" name="inputPass1">
</div>
</div>
</div>
</div>
</div>
</div>
<div id="login-content">
<div class="form-group">
<button type="submit" class="btn btn-default signin-btn" onclick="formhash(this.form, this.form.inputPass1);">Sign In</button>
</div>
</form>
Process Login Page
<?php
header('P3P: CP="NOI ADM DEV COM NAV OUR STP"');
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['inputEmail1'], $_POST['p'])) {
$email = $_POST['inputEmail1'];
$password = $_POST['p']; // The hashed password.
exit($email);
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: ../index.php');
} else {
// Login failed
header('Location: ../index.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
Login Function
//checks login info against db
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, fname, lname, pass, salt, type_id
FROM users
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $fname, $lname, $db_password, $salt, $user_type);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$user_type = preg_replace("/[^0-9]+/", "", $user_type);
$_SESSION['user_id'] = $user_id;
$_SESSION['user_type'] = $user_type;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$fname . $lname);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
The answer was in the javascript. Basically IE8 does not allow changing the 'type' of a field and there was a javascript function that hashed the password and then put the value in a new field where it set the type to hidden. I just made the field already set to hidden and then it worked.

Categories