CodeIgniter Button does not Trigger Action - php

I have been searching through various questions on the site with no luck. The closest I got to an answer, as far as I can tell, was through the following question: CodeIgniter's form action is not working properly.
The problem is that when I press the login button nothing happens so the action property in the HTML form is not being triggered. I have looked at my routes as well with no luck.
The HTML code is in my view folder and is the following:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-body">
<form role="form" method="post" action="<?php echo base_url() ?>index.php/login">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" name="username" type="username" required>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" required>
</div>
<a type="submit" id="login-button" style="navy" class="btn btn-lg btn-success btn-block">Login</a>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
My controller is called pages.php, and it's function, login is the following:
public function login()
{
$this->load->helper('form');
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($username != false && $password != false)
{
$loginDetails = $this->pages_model->retrieveLoginDetails($username, $password);
if ($loginDetails != false)
{
if ($loginDetails['username'] == $username && $loginDetails['password'] == $password)
{
$this->load->view ('home');
}
else
{
$this->view();
echo "details dont match";
}
}
else
{
$this->view();
echo "nothing received from db";
}
}
else
{
$this->view();
echo "no details entered";
}
}
I am only concerned with going to the home page. By calling the view function I am just returning to the login screen. I will adjust the naming appropriately once I can get this to work. The pages model contains the following function to retrieve the login data from the database:
public function retrieveLoginDetails ($username, $password)
{
$loginDetails['username'] = $this->db->get_where('user_details', $username);
if (! empty ($loginDetails['username']))
{
$loginDetails['password'] = $this->db->get_where('user_details', $password);
return $loginDetails;
}
return false;
}
Any help would be greatly appreciated. Thanks.

Use
<input type="submit" value="Login" class="btn btn-lg btn-success btn-block" />
In place of
<a type="submit" id="login-button" style="navy" class="btn btn-lg btn-success btn-block">Login</a>
To know more check out this : http://www.w3schools.com/tags/tag_a.asp

I don't know direct anwser, but did you check what exactly is your server returning and where are data beeing sent. LiteBug FTW ;)
If there isn't any data beeing sent, you should probally check your .js files.

Related

Breaking login flow if already logged in with another session

I am working on a codeigniter 3 app and ive recently implemented a session checker that deletes a user session if they're already logged in. Now we want a modal box to pop up if the user is already logged in with another session. I am able to get a modal box to pop up using a button but i want to implement it into the original flow of the login system. As it is the login form takes you straight to the validate login system. This is the login form now:
<form action="<?php echo site_url('login/validate_login/user'); ?>" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
The button at the moment goes straight to this login function:
public function validate_login($from = "") {
$email = $this->input->post('email');
$password = $this->input->post('password');
$credential = array('email' => $email, 'password' => sha1($password), 'status' => 1);
// Checking login credential for admin
$query = $this->db->get_where('users', $credential);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('user_id', $row->id);
$this->session->set_userdata('role_id', $row->role_id);
$this->session->set_userdata('role', get_user_role('user_role', $row->id));
$this->session->set_userdata('name', $row->first_name.' '.$row->last_name);
$this->delete_session_user_id();
$this->session->set_flashdata('flash_message', get_phrase('welcome').' '.$row->first_name.' '.$row->last_name);
if ($row->role_id == 1) {
$this->session->set_userdata('admin_login', '1');
redirect(site_url('admin/dashboard'), 'refresh');
}else if($row->role_id == 2){
$this->session->set_userdata('user_login', '1');
$this->set_session_user_id();
redirect(site_url('home/my_courses'), 'refresh');
}
}else {
$this->session->set_flashdata('error_message',get_phrase('invalid_login_credentials'));
redirect(site_url('home/login'), 'refresh');
}
}
I created this function to pull the user id from the emails:
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
This function can get the user id based on the email supplied.
Then I use this function to check if there is a session and return false if there are 0 results and true if there is a session with that user id. So if its false they should be able to log in and the modal pop-up shouldnt open but if its true it should open.
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
I think this is the best approach without having to redo the entire login flow. Perhaps someone can advise if this is the best approach or if in fact i should change the entire flow.
Thanks
Here is the previous problem I had which I have answered myself
https://stackoverflow.com/questions/62458226/codeigniter-3-stop-multiple-logins-using-ci-sessions-database
UPDATE Added to clarify my problem
Well the problem is when a login is attempted from another device it should logout the other active session. So if o logged in on my desktop in a new browser or even my phone with the same user ID the active session should end, at the moment it does so without warning the user. So I want to have a modal pop up warning the user that there is an active session currently running with this user id
You need to implement an Ajax call which will check whether the user is already logged in or not. If the user is not logged In than you can proceed to login otherwise trigger your popup open to display the message.
Here the user has choices to log in or not, If users choose to login then you can unbind the event on submit and let the user go ahead.
I have made some changes to your HTML file. Please check below -
Your HTML template
<form action="<?php echo site_url('login/validate_login/user'); ?>" id="login-form" onSubmit="return checkUserSession();" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="button" id="modal-submit-button" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
<script>
/** Trigger function on form submit whether to check user logged in */
function checkUserSession(){
var email = $("#login-email").val();
$.ajax({
url: "<?php echo site_url('login/checkUserSession'); ?>",
type: 'POST',
data: { 'email': email},
success: function(status){
if(status == true) { // User is already logged in somewhere, display the messege.
$("#login").modal();
return false;
} else { // User is not logged in, submit the form
return true;
}
}
});
}
/** Allow user to log in with exception */
$("#modal-submit-button").on("click", function(){
$("#login").modal('hide'); // hide the modal
$("#login-form").attr("onSubmit", ""); // unbind the function
$("#login-form").submit(); // submit login form
})
</script>
Controller -
<?php
/** Function to check user logged in or not */
public function checkUserSession() {
$user_email = $this->input->post('email');
$userId = $this->get_user_id($user_email);
$response = $this->user_has_session($userId);
echo $response;
}
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
?>

How to pass and catch variable when the method is POST then the route is GET?

I'm developing a web application, and I want to pass variable called ID when the form method is post that linked to open other form but in the config/routes I'm using $routes[page_A][get] = 'Controller' not $routes[page_A][post] = 'Controller'.
I'm using Codeigniter framework here, I've tried to change the controller with $this->input->get('id') but it doesn't work and I don't have any idea whats really happen in my codes.
The Sender Form View code
<form action="<?= base_url().'progres_save'; ?>" method="POST">
<div class="form-group">
<div class="form-row">
<label for="idJobOrder">ID Job Order</label>
<input type="text" name="idJobOrder" class="form-control" value="<?php echo $rd[0]->kodejobglobal; ?>" readonly>
</div>
</div>
<div class="form-group">
<div class="form-row">
<a class="btn btn-primary col-xl-1 col-sm-1 mb-1 ml-auto mr-0 mr-md-2 my-0 my-md-3" href="job" id="back" role="button"><i class="fas fa-fw fa-arrow-left"></i> Back</a>
<button class="btn btn-primary btn-block col-xl-1 col-sm-1 mb-1 mr-0 mr-md-2 my-0 my-md-3">Save <i class="fa fa-fw fa-arrow-right"></i></button>
<input type="hidden" name="id" value="<?php echo $rd[0]->kodejobspesifik ?>">
</div>
</div>
</form>
The Sender Form Controller code
public function save()
{
$idglobal = $this->input->post('idJobOrder');
$data = array('jobnya' => $idglobal );
$this->Model_joborder->save_pg($data,'lapharian');
redirect('progres_material');
}
The Config Routes code
$route['progres_save']['get']='error';
$route['progres_save']['post']='save';
$route['progres_material']['get']='matused';
$route['progres_material']['post']='error';
The Recipient Form Controller code
public function matused()
{
$id = $this->input->get('id');
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
The Recipient Form View code
<form method="POST" action="<?= base_url().'matsave'; ?>">
<div class="form-group">
<div class="form-row">
<?php if (isset($rd[0])) {?>
<input type="hidden" value="<?php echo $rd[0]->jobspesifiknya; ?>" name="idClient" class="form-control" placeholder="First name" readonly>
<?php } ?>
</div>
</div>
</form>
What I expect is the input id value from Sender will be passed and catch on Recipient form as input idClient. Can anyone her help me to find out the solution? Thank you.
You can use PHP global variable $_REQUEST to capture the data if you are not sure about the request type like this,
public function matused()
{
$id = $_REQUEST['id'];
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
You forgot to include the id data on the redirect after the save() method is called, so you will not get anything by calling $this->input->get('id').
To solve this, pass the id data along with the redirect :
redirect('progres_material?id=' . $this->input->post('id'));
But that of course it will gives you an extra parameter on the url. If you don't want additional parameter, you could alternatively use session to pass id data while redirecting, on CodeIgniter there is a method called set_flashdata to do this :
$this->session->set_flashdata('id', $this->input->post('id'));
redirect('progres_material');
And to get the id session data on the matused() method, use the following code :
$id = !empty($this->session->flashdata('id')) ? $this->session->flashdata('id') : $this->input->get('id');

mysql check if username and password matches in database using laravel php

I have small issue with authentication when user try to login but the username and password not matched in table how can return to login page with error massage
login.blade.php
<form class="login-box animated fadeInUp" action="valdateData" method="POST" >
{{csrf_field()}}
<div class="box-header">
<h2>Log In</h2>
</div>
<label for="username">Username</label>
<br/>
<input type="text" id="username" name="username">
<br/>
<label for="password">Password</label>
<br/>
<input type="password" id="password" name="password">
<br/>
<button type="submit">Sign In</button>
<br/>
<p class="small">Forgot your password?</p>
</form>
web.php
Route::post('/testgetvalue','OrdersController#GetValues');
Route::get('/ES','OrdersController#PrepareIndex');
Route::get('/loginForm','LoginController#ShowLoginPage');
Route::post('/valdateData','LoginController#checkValidate');
Route::post('login/{id}','LoginController#ShowErrorMassege');
LoginController.php
public function ShowLoginPage()
{
return view('/loginForm');
}
public function checkValidate(Request $request)
{
$username=$request->input('username');
$password=$request->input('password');
$isVald=true;
$checkValdate = \DB::table('authentications')
->where(['username'=>$username,'password'=>$password])
->get();
if(count($checkValdate) > 0)
{
$isVald=true;
session()->set('UserValidate','true');
session()->set('username',$username);
//$value=session()->get('test');
// echo "session "+$value;
return redirect('/es');
} else {
return redirect('/login/'.$isVald);
}
}
in this part
return redirect('/login/'.$isVald);
how can return to login page with error message
thanks
$validator = Validator::make($request->all(), [
'username'=>'required|min:3|max:30',
'password'=>'digits_between:1,5000',
]);
if ($validator->fails())
{
return redirect()->back()->with('error', sprintf('Server failed provided data validation.Please try again and follow the validation rules as instructed.'));
}
Here is a example of how you can do it, depends on your validatin rules. You can also define partials with a costum message foreach error, you should also use "use Illuminate\Support\Facades\Validator;" in your controller

PHP form only returning empty array

I am working on a code segment that is a messaging function next to a list of names. On the page there is an envelope and when you click it a pop-up window appears with a text area inside of it. I would like to be able to fill that textarea with characters and send it as a message using my already functioning sendMessage function. I know my sendMessage function works and I've isolated the issue to the return given by the submit button. How do I get my submit button to POST the textarea to the page (keep in mind there are 2+ forms on this page). The code looks like this:
if (empty($_POST) === false) {
print_r($_POST);
$blah = $_POST;
echo "<script>window.top.location='asd.$blah'</script>";
}
if (empty($_POST['Send']) === false) {
echo "<script>window.top.location='../hidden/PNMasdd.php?gpa=$var1&year=$var2&major=$var3&sport=$var4'</script>";
echo 'YOU ARE IN THE SENDING MESSAGE FIELD';
if( empty ($_POST['message_full']))
{
$errors[] = 'All fields must be filled in!';
//print_r($errors);
}
if(empty($_POST) === false && empty($errors) === true)
{
$receiver_id = $temp_user['id'];
$sender_id = $user_data['id'];
$type = 0;
if(empty($is_Convo))
{
$is_Convo = 0;
}
$blahVar = $user_data['id'] . ',';
$message = str_replace("\r\n", "<br>", $_POST['message_full']);
$message_data = array(
'sender_id' => $user_data['id'],
'receiver_id' => $receiver_id,
'message_full' => $message,
'is_opened' => $blahVar,
'isConvo' => $is_Convo,
'type' => $type
);
//Put data limit code here
send_message($message_data);
$my_exten = "Messages/messages.php";
$noti_data = array(
'id_receive' => $receiver_id,
'id_sent' => $user_data['id'],
'type' => 1,
'exten' => $my_exten
);
notify($noti_data);
echo '<center>';
echo '<div class="alert alert-info">
<strong>It sent!</strong> You have sent a message successfully!
</div>
';
echo '</center>';
}
else{
echo output_errors($errors);
}
}
?>
<form id="wow" name="wow" action="" method="POST">
<div class="row">
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<center>
<textarea maxlength="100000" data-msg-required="Please enter your message." rows="10" cols="100%" class="form-control" name="message_full" id="message_full"></textarea>
</center>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<table width=90%><td width=45%><button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button></td><td width=45%>
<button type="submit" value="Send Message" name="Send" onclick="document.getElementById('wow').submit()" class="btn btn-primary">Send</button>
As pointed out in the comments, the buttons need to be inside your form.
Your setup is a bit odd for my taste, but try this out.. it will mostlikely need some tweaks and i'm not sure about the cancel button..
<form id="wow" name="wow" action="" method="post" >
<div class="form-group required">
<div class="col-md-12">
<textarea name="message_full" id="message_full" rows="10" cols="100%" class="form-control" maxlength="10000" placeholder="Please enter your message." autocomplete="off"></textarea>
</div>
</div>
<div class="buttons"> <!-- add css for this or change the class to yours.. -->
<input class="btn btn-default" data-dismiss="modal" value="Cancel" />
<input class="btn btn-primary" type="submit" value="Send Message" />
</div>
</form>
As #Barmar just said, you don't have any field named 'Send'. You should change:
if (empty($_POST['Send']) === false)
to:
if (empty($_POST['message_full']) === false)
(Edit)
Only the fields inside your form will get to $_POST superglobal, the submit button will not get there

Using Cjax to POST data in CodeIgniter

I'm trying to POST some data using Cjax in CodeIgniter.
My view is:
<?php
require_once(FCPATH . 'ajaxfw.php');
$ajax->click('#subscribesubmit' , $ajax->form('ajax.php?subscriber/add/'));
?>
<div class="col-md-4">
<form class="form-inline subscribe-box" role="form" method="post">
<div class="form-group">
<label class="sr-only" for="subscribemail">Email address</label>
<input type="text" class="form-control" id="subscribemail" name="subscribemail" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-default" id="subscribesubmit">Subscribe</button>
</form>
</div>
This view is loaded in controller index().
My subscriber controller:
class Subscriber extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('email');
$this->load->model('subscriber_model');
require_once(FCPATH.'ajaxfw.php');
}
public function add($subscribemail) {
$ajax = ajax();
//$email = $this->input->post('subscribemail');
echo $subscribemail;
$data['status'] = $this->subscriber_model->new_subscriber($subscribemail);
}
}
}
Try this:
in your code block replace to:
require_once(FCPATH . 'ajax.php');
instead of:
require_once(FCPATH . 'ajaxfw.php');
You should include ajax.php instead of ajaxfw.php (ajax.php would include itself ajaxfw.php if it needs to)

Categories