Dynamic dependant dropdown list in codeigniter - php

I have three Dynamic Dependant Dropdown Lists in Codeigniter:-
One of them represents company names
According to the company I choose I want to show that particular company's managers on one of my other dropdown
The company's staffs are shown on my third dropdown.
Both manager and staff are saved in same column called role_name in role_settings table of database.
So far i proceed my code to get list of managers on dropdown, but when i run my code nothing happens, and I actually dont know how to get staff's list on my other dropdown. Here is my code.
Project.php Controller:-
<?php
class Project extends CI_controller
{
function __construct()
{
parent::__construct();
// if(!$this->session->userdata('admin'))
// redirect('admin');
$this->load->model('project_model');
}
function index ()
{
$data['project'] = $this->project_model->getProjectDetails();
$this->load->view('admin/project/index',$data);
}
function add()
{
$this->form_validation->set_rules('Pname', 'Project Name', 'required');
$this->form_validation->set_rules('Cname', 'Client Name' , 'required');
$this->form_validation->set_rules('PassignTo', 'Company', 'required');
$this->form_validation->set_rules('manager', 'Manager' , 'required');
$this->form_validation->set_rules('staff', 'Support Staff', 'required');
$data['company_name'] = $this->project_model->getAllCompanyName();
$data['project'] = $this->project_model->getProjectDetails();
if ($this->form_validation->run() ==true)
{
$this->project_model->add();
$this->session->set_flashdata ('success','Project Added Sucessfully');
redirect('admin/project/index',$data);
}
else{
$this->load->view('admin/project/add',$data);
}
}
function edit($id)
{
$data['project'] = $this->project_model->getById($id);
$data['company_name'] = $this->project_model->getAllCompanyName();
$this->load->view('admin/project/edit', $data);
}
function update($id)
{
$this->project_model->update($id);
$this->session->set_flashdata ('success','Project updated Sucessfully');
redirect('admin/project/index');
}
function delete($id)
{
$this->project_model->delete($id);
$this->session->set_flashdata ('success','Project Deleted Sucessfully');
redirect('admin/project/index');
}
function getAllManger()
{
print_r($_REQUEST);
die;
if ($this->input->post('company_id'))
{
echo $this->project_model->
getAllManger($this->input->post('company_id'));
}
}
}
Project_model.php Model Code:-
<?php
class Project_model extends CI_Model
{
function getProjectDetails()
{
//table (projects)
return $this->db->get('projects')->result();
}
function getById($id)
{
return $this->db->get_where('projects',array('id'=>$id))->row();
}
function add()
{
$arr['project_name'] = $this->input->post('Pname');
$arr['client_name'] = $this->input->post('Cname');
$arr['company'] = $this->input->post('PassignTo');
$arr['project_manager'] = $this->input->post('manager');
$arr['support_staff'] = $this->input->post('staff');
$this->db->insert('projects',$arr);
}
function update($id)
{
$arr['project_name'] = $this->input->post('Cname');
$arr['client_name'] = $this->input->post('regNo');
$arr['company'] = $this->input->post('company');
$arr['project_manager'] = $this->input->post('manager');
$arr['support_staff'] = $this->input->post('staff');
$this->db->update('projects',$arr);
}
function delete($id)
{
$this->db->where(array('id'=>$id));
$this->db->delete('projects');
}
function getAllCompanyName()
{
$this->load->model('company_model');
$this->company_model->getCompanyDetails();
$this->db->order_by('company_name', 'ASC');
$query = $this->db->get('company_details');
//$query = $this->db->query('SELECT company_name FROM company_details');
return $query->result();
}
function getAllManger($company_id)
{
$this->db->where('id',$company_id);
$this->db->oredr_by('role_name', 'ASC');
$query = $this->db->get('roles_settings');
$output = '<option value="">Select Mangaer</option>';
foreach($query->result() as $row)
{
$output .= '<option value=" '.$row->manager_id.'">'.$row->project_manager. '</option>';
}
return $output;
}
function getAllStaff()
{
}
}
add.php View
<?php
$this->load->view('admin/header');
?>
<div class="main-sec">
<div class="row">
<div class="col-md-8">
<nav>
<ol class="breadcrumb">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item">Projects</li>
<li class="breadcrumb-item active">Add Projects</li>
</ol>
</nav>
</div>
<div class="col-md-4">
<!-- <button class="btn btn-outline-primary float-right" id="addProjects"><i class="fa fa-plus-circle" aria-hidden="true"></i> Add Projects</button> -->
<?php
if($this->session->flashdata('success'))
{
?>
<div class="alert alert-success" role="alert">
<?php
echo $this->session->flashdata('success');
?>
</div>
<?php
}?>
</div>
</div>
<div class="main-sec-contant">
<div class="ProjectsAdd" >
<h2 class="heading">Add Project</h2>
<?php echo form_open('project_add'); ?>
<div class="row">
<div class="form-group col-md-4">
<label for="text">Project Name</label>
<input type="text" class="form-control" id="Pname" placeholder="Name" name="Pname" value="<?php echo set_value('Pname'); ?>">
<div class="alert-danger"><?php echo form_error('Pname'); ?></div>
</div>
<div class="form-group col-md-4">
<label for="pwd">Client Name</label>
<input type="text" class="form-control" id="Cname" placeholder="Client Name" name="Cname" value="<?php echo set_value('Cname'); ?>">
<div class="alert-danger"><?php echo form_error('Cname'); ?></div>
</div>
<div class="form-group col-md-4">
<label for="pwd">Project Assign To</label>
<select class="form-control" id="company" name="PassignTo" value="<?php echo set_value('PassignTo'); ?>">
<div class="alert-danger"><?php echo form_error('PassignTo'); ?></div>
<?php
foreach($company_name as $row )
{
echo '<option value="'.$row->id.'">'.$row->company_name.'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="pwd">Project Manager</label>
<select class="form-control" id="manager" name="manager" value="<?php echo set_value('manager'); ?>">
<div class="alert-danger"><?php echo form_error('manager'); ?></div>
<option value="">Select Mangaer</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="pwd">Add Support Staff</label>
<select id="addStaffMulti" multiple="multiple" name="staff" value="<?php echo set_value('staff'); ?>">
<div class="alert-danger"><?php echo form_error('staff'); ?></div>
<option value="">Select Staff</option>
</select>
</div>
<div class="col-md-12">
<div class="btn-section float-right">
<button class="btn btn-outline-primary" type="submit" name="create" ><i class="fa fa-plus-circle" aria-hidden="true"></i> Create</button>
<a href="<?php echo site_url ('project');?>"> <button class="btn btn-danger float-right" id="cancelProjects" type="button" name="cancel" onClick="window.location.href=admin/project" ><i class="fa fa-plus-circle" aria-hidden="true"></i> Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<?php
$this->load->view('admin/footer');
?>
JQUERY AJAX CODE:-
<script>
$(document).ready(function()
{
$('#company').change(function(){
var company_id = $('#company').val();
if(company_id != '')
{
$.ajax({
url:"<?php echo base_url();?>
project/getAllManger",
method:"POST",
data:{company_id:company_id },
success:function(data)
{
$('#manager').html(data);
$('#addStaffMulti').html(' <option value="">Select Staff</option>');
}
});
}
else
{
$('#manager').html('<option value="">Select Mangaer</option>');
$('#addStaffMulti').html('<option value="">Select Staff</option>');
}
});
$()
});
});
</
<script>
And image below is image of role_settings table in database, I am basically trying to display all managers from role_name column in my Select Manager dropdown list and display the rest of the role_name column datas on Add stuff dropdown.

Solved the problem by making below changes in my code,also proceeded the form validation.
Project.php controller
<?php
class Project extends CI_controller
{
function __construct()
{
parent::__construct();
// if(!$this->session->userdata('admin'))
// redirect('admin');
$this->load->model('project_model');
}
public function index ()
{
$data['company_name'] = $this->project_model->getAllCompanyName();
$data['project'] = $this->project_model->getProjectDetails();
$this->load->view('admin/project/index',$data);
}
function add()
{
$this->form_validation->set_rules('Pname', 'Project Name', 'required');
$this->form_validation->set_rules('Cname', 'Client Name' , 'required');
$this->form_validation->set_rules('PassignTo', 'Company', 'required');
$this->form_validation->set_rules('manager', 'Manager' , 'required');
$this->form_validation->set_rules('staff', 'Support Staff', 'required');
$data['company_name'] = $this->project_model->getAllCompanyName();
$data['project'] = $this->project_model->getProjectDetails();
if ($this->form_validation->run() ==true)
{
$this->project_model->add();
$this->session->set_flashdata ('success','Project Added Sucessfully');
redirect('admin/project/index',$data);
}
else{
$this->load->view('admin/project/add',$data);
}
}
function edit($id)
{
$data['project'] = $this->project_model->getById($id);
$data['company_name'] = $this->project_model->getAllCompanyName();
$this->load->view('admin/project/edit', $data);
}
function update($id)
{
$this->project_model->update($id);
$this->session->set_flashdata ('success','Project updated Sucessfully');
redirect('admin/project/index');
}
function delete($id)
{
$this->project_model->delete($id);
$this->session->set_flashdata ('success','Project Deleted Sucessfully');
redirect('admin/project/index');
}
public function getManager()
{
//echo json_encode ("sdf"); die;
//print_r($_REQUEST);
//die;
$company_name = $this->input->post('company_name');
$getallmanager = $this->project_model->get_manager_query($company_name);
$getallstaff = $this->project_model->get_all_staff($company_name);
$all_the_mangers = '';
$all_the_staffs = '';
if(count($getallmanager)>0)
{
foreach ($getallmanager as $manager){
$all_the_mangers .='<option value="' .$manager->role.'">'.$manager->first_name.'</option>';
}
}
if(count($getallstaff)>0)
{
foreach ($getallstaff as $staff){
$all_the_staffs .='<option value="' .$staff->role.'">'.$staff->first_name.'</option>';
}
}
$result = array('manager'=>$all_the_mangers,'staffs'=>$all_the_staffs);
echo json_encode($result);die;
}
}
And added below javaScript at the end of my project.php view .
<script type="text/javascript">
$(document).ready(function(){
$('#company').on('change' , function() {
var company_name = $(this).val();
if(company_name == '')
{
$('#manager').prop('disabled', true);
$('#addStaffMulti').prop('disabled', true);
}
else
{
$('#manager' ).prop('disabled', false);
$('#addStaffMulti').prop('disabled', false);
//var url = "<?php echo base_url()?>getManager";
//alert(url);
//return false;
$.ajax({
url:"<?php echo base_url()?>getManager",
type: "POST",
data: { 'company_name' : company_name},
dataType:'json',
success: function(data){
//alert('ok');
console.log(data);
$('#manager').html(data.manager);
$('#addStaffMulti').html(data.staffs);
$('#addStaffMulti').multiselect('rebuild');
},
error: function(event){
console.log(event);
alert('Error occur...');
}
});
}
});
});
</script>

Related

codeigniter form login validation using modal

I am having a login modal form which is correctly validating but i am having a small problem that it is nt returning false statement on login modal such as Invalid user or password. Whereas in response i see wrong password entered and all html . But no message is printing on form.
here is my view:
Sign In / Order |
<div class="modal fade" id="loginmodel" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content martop105">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title text_center" id="exampleModalLabel">Login</h4>
</div>
<div class="modal-body">
<form >
<div class="row margin0 text_center">
<div class=" col-md-12 col-sm-12 col-xs-12" >
<input type="email" id="email" placeholder="Email*" class="form-control">
</div>
<br>
<div class="col-md-12 col-sm-12 col-xs-12 martop20">
<input type="Password" id="password" placeholder="Password*" class="form-control">
</div>
<br>
<div class="checkbox col-md-12 col-sm-12 col-xs-12 pull-left martop20" >
<label class="pull-left"><input name="remember" type="checkbox" value="Remember Me"> Remember Me</label>
</div>
<div class=" col-md-12 col-sm-12 col-xs-12 pull-left text_blue martop20" >
<a href="#" class="text_blue pull-left">
Forgot password?
</a>
</div>
</div>
<br>
<div class="row margin0 ">
<button type="button" onclick="save();" class="btn btn-info btn-lg marleft20 active">Login</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<script>
function save(){
// alert('ddsfsf');
var email=$('#email').val();
var password=$('#password').val();
// alert(email);
//alert(gender);
$.ajax({
url: '<?php echo base_url();?>Choice/login',
type: 'POST',
data: {
email: email,
password:password
},
dataType: 'text',
success: function(data) {
// console.log(data);
// alert(data);
// alert("Succesfully Saved");
// location.reload(false);
}
});
}
</script>
controller
class Choice extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->database();
$this->load->model('login_model','login_model');
$this->load->library('session');
$this->load->library('eway');
$this->load->model('Catering_model','catering_model');
// $this->load->helper('utility');
$this->load->helper('url');
}
public function login()
{
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[choicelunchuser.email]');
$this->form_validation->set_rules('password','Password','required|callback_basisdata_cek');
if($this->form_validation->run()==false)
{
$this->load->view('ChoiceLaunch/index');
}
else{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['id'];
$data['email'] = $session_data['email'];
$this->load->view('ChoiceLaunch/index',$data);
}
else{
$this->load->view('ChoiceLaunch/index');
}
}
}
public function basisdata_cek()
{
$username= $this->input->post('email');
$password=$this->input->post('password');
// echo $username.' '.$password;
$result=$this->login_model->loginemail($username,$password);
// echo ('fsf'.$result[0]);
// echo ('fsf'.$result[1]);
if($result)
{
$sess_array = array();
foreach ($result as $row)
{
$sess_array = $arrayName = array('id' => $row->id,'email'=> $row->email);
$this->session->set_userdata('logged_in',$sess_array);
// $ci = & get_instance();
//$ci->session->set_userdata("logged_in",$sess_array);
}
return true;
}
else{
//echo $username.' '.$password;
$this->form_validation->set_message('basisdata_cek','Invalid user or password');
return false;
}
}
}
for illustration kindly see pic:
You should add <?php echo validation_errors(); ?> to your view
You can use flash data to print your error message. In your controller
Change
else{
$this->load->view('ChoiceLaunch/index');
}
To
else{
$this->session->set_flashdata('yes', 'Invalid username or password');
redirect('ChoiceLaunch/index');
}
In your login view page add
<?php if($this->session->flashdata('yes')){ ?>
<span style="color:red;"><?php echo $this->session->flashdata('yes'); ?></span>
<?php } ?>
You should load library session.
$this->load->library('session');
Make sure have set base url in config.php
$config['base_url'] = 'http://localhost/projectname/';
dataType to json
function save(){
var email=$('#email').val();
var password=$('#password').val();
$.ajax({
url: "<?php echo base_url('choice/login');?>",
type: 'POST',
data: {
email: email,
password:password
},
dataType: 'json',
success: function(data) {
if ($data['success'] == false) {
// $('#somediv').text($data['error']);
$('#somediv').html($data['error']);
}
if ($data['success'] == true) {
alert('yes')
}
}
});
}
Controller
public function login() {
$data = array();
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[choicelunchuser.email]');
$this->form_validation->set_rules('password','Password','required|callback_basisdata_cek');
if ($this->form_validation->run() == false) {
$data['success'] = false;
$data['error'] = validation_errors();
} else {
// Set the session data
$data['success'] = true;
}
echo json_encode($data);
}
Then You will need to create another ajax function so when click login button to load model will display it.

Edit the Logged In Profile with Ajax

I'm new to CodeIgniter and need some help :).
I managed to build a CRUD functions with ajax over some tutorials and I can Edit, Add new, Delete all user shown on my page. What I want now is when i Login with a user I just want the Logged in Profile to be Edited, not others. Please if someone can help me how can I manage to do that. Thank You in Advance.
Employee.php Controller
<?php
defined('BASEPATH') OR exit('No direct sripct access allowed');
Class Employee extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Employee_m', 'm');
}
function index()
{
$this->load->view('employee/index');
}
public function showAllEmployee()
{
$result = $this->m->showAllEmployee();
echo json_encode($result);
}
public function add_user()
{
$result = $this->m->add_user();
$msg['success'] = false;
$msg['type'] = 'add';
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
public function edit_user()
{
$result = $this->m->edit_user();
echo json_encode($result);
}
public function update_user()
{
$result = $this->m->update_user();
$msg['success'] = false;
$msg['type'] = 'update';
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
public function delete_user()
{
$result = $this->m->delete_user();
$msg['success'] = false;
if ($result) {
$msg['success'] = true;
}
echo json_encode($msg);
}
Employee_m Model
<?php defined('BASEPATH') OR exit('No direct sripct access allowed');
class Employee_m extends CI_Model
{
public function showAllEmployee()
{
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return $query->result();
}
else
{
return false;
}
}
public function add_user()
{
$field = array(
'firstname' => $this->input->post('txtFirstName'),
'lastname' => $this->input->post('txtLastName'),
'username' => $this->input->post('txtUsername'),
'user_email' => $this->input->post('txtUserEmail'),
'user_password' => $this->input->post('txtUserPassword')
);
$this->db->insert('users',$field);
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
public function get_id(){
$id = $this->input->get('id');
$this->db->where('id',$id);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return $query->result();
}
else
{
return false;
}
}
public function update_user()
{
$id = $this->input->post('txtId');
$field = array(
'firstname' => $this->input->post('txtFirstName'),
'lastname' => $this->input->post('txtLastName'),
'username' => $this->input->post('txtUsername'),
'user_email' => $this->input->post('txtUserEmail'),
'user_password' => $this->input->post('txtUserPassword')
);
$this->db->where('id',$id);
$this->db->update('users',$field);
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
function delete_user()
{
$id = $this->input->get('id');
$this->db->where('id',$id);
$this->db->delete('users');
if ($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
}
Index View
<?php $this->load->view('components/page_head'); ?>
<?php
if (isset($this->session->userdata['logged_in'])) {
$username = ($this->session->userdata['logged_in']['username']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: user_authentication");
}
?>
<div class="col-sm-9">
<div class="alert alert-success" style="display: none;">
</div>
<button id="btnAdd" class="btn btn-success">Add New</button>
<table class="table table-bordered table-responsive" style="margin-top: 20px;">
<thead>
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Username</td>
<td>e-Mail</td>
<td>Actions</td>
</tr>
</thead>
<tbody id="showdata">
</tbody>
</table>
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal">
<input type="hidden" name="txtId" value="0">
<div class="form-group">
<label class="label-control col-md-4">First Name</label>
<div class="col-md-6">
<input type="text" name="txtFirstName" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Last Name</label>
<div class="col-md-6">
<input type="text" name="txtLastName" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Username</label>
<div class="col-md-6">
<input type="text" name="txtUsername" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">e-Mail</label>
<div class="col-md-6">
<input type="email" name="txtUserEmail" class="form-control">
</div>
</div>
<div class="form-group">
<label class="label-control col-md-4">Password</label>
<div class="col-md-6">
<input type="password" name="txtUserPassword" class="form-control" placeholder="******">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Confirm Delete</h4>
</div>
<div class="modal-body">
Do you want to delete this record?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnDelete" class="btn btn-danger">Delete</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
$(function () {
showAllEmployee();
// Add New
$('#btnAdd').click(function () {
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Add new user');
$('#myForm').attr('action','<?php echo base_url() ?>employee/add_user');
});
$('#btnSave').click(function () {
// alert('test');
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// validate the form
var firstname = $('input[name=txtFirstName]');
var lastname = $('input[name=txtLastName]');
var username = $('input[name=txtUsername]');
var user_email = $('input[name=txtUserEmail]');
var user_password = $('input[name=txtUserPassword]');
var result = '';
if (firstname.val()==''){
firstname.parent().parent().addClass('has-error');
}else {
firstname.parent().parent().removeClass('has-error');
result +='1';
}
if (lastname.val()==''){
lastname.parent().parent().addClass('has-error');
}else {
lastname.parent().parent().removeClass('has-error');
result +='2';
}
if (username.val()==''){
username.parent().parent().addClass('has-error');
}else {
username.parent().parent().removeClass('has-error');
result +='3';
}
if (user_email.val()==''){
user_email.parent().parent().addClass('has-error');
}else {
user_email.parent().parent().removeClass('has-error');
result +='4';
}
if (user_password.val()==''){
user_password.parent().parent().addClass('has-error');
}else {
user_password.parent().parent().removeClass('has-error');
result +='5';
}
if(result == '12345'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function (response) {
if (response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('User '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function () {
alert('Could not add Data ');
}
});
}
});
//edit
$('#showdata').on('click', '.item-edit', function() {
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('edit user');
$('#myForm').attr('action','<?php echo base_url() ?>employee/update_user');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>employee/edit_user',
data: {id: id},
async: false,
dataType: 'json',
success: function(data) {
$('input[name=txtFirstName]').val(data.firstname);
$('input[name=txtLastName]').val(data.lastname);
$('input[name=txtUsername]').val(data.username);
$('input[name=txtUserEmail]').val(data.user_email);
$('input[name=txtUserPassword]').val(data.user_password);
$('input[name=txtId]').val(data.id);
},
error: function() {
alert('Could not Edit Data');
}
});
});
//delete
$('#showdata').on('click', '.item-delete', function () {
var id = $(this).attr('data');
$('#deleteModal').modal('show');
$('#btnDelete').unbind().click(function () {
$.ajax({
type: 'ajax',
method: 'get',
async: false,
url: '<?php echo base_url() ?>employee/delete_user',
data: {id: id},
dataType: 'json',
success: function (response) {
if(response.success){
$('#deleteModal').modal('hide');
$('.alert-success').html('User deleted successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function () {
alert('Error deleting');
}
});
});
});
//function
function showAllEmployee() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>employee/showAllEmployee',
async: false,
dataType: 'json',
success: function (data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<td>'+data[i].id+'</td>'+
'<td>' + data[i].firstname + '</td>' +
'<td>' + data[i].lastname + '</td>' +
'<td>' + data[i].username + '</td>' +
'<td>' + data[i].user_email + '</td>' +
'<td>' +
'Edit' +
'Delete' +
'</td>' +
'</tr>';
}
$('#showdata').html(html);
},
error: function () {
alert('Could not get Data from Database');
}
});
}
});
</script>
</div>
<div class="col-sm-3">
<?php
echo "Hello <b id='welcome'><i>" . $username . "</i> !</b>";
echo "<br/>";
echo "Your ID is " . $id;
echo "<br/>";
?>
Logout
</div>
<?php $this->load->view('components/page_tail'); ?>
You need to fetch that user details to index page to avoid edting for other or need to set some condition such as passing users id on edit check if it same as edit id and then proceed for edit opertaion or else return some message

Codeigniter: redirect page to user profile after update

I want to show an updated profile page of users on my site. The update on database is actually working but i want my userprofile page to show the updated datas once it clicked the submit button. What will I add here D:
MemberLoginController.php (controller)
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class MemberLoginController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('MemberLoginModel');
}
public function home(){
$this->load->view('pages/index');
}
public function userprofile(){
$this->load->view('member/userprofile');
}
public function useredit(){
$this->load->view('member/useredit');
}
public function memberlogin(){
$this->form_validation->set_error_delimiters('<p class=error>','</p>');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run()){
// Perform Actions after getting valid form inputs
$data = array(
'email' => $this->input->post('email'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
redirect('index.php/MemberLoginController/members');
}else
$this->load->view('pages/index');
}
public function members(){
if($this->session->userdata('is_logged_in')){
$vis = "hidden";
$id = $this->session->userdata('id');
$this->load->model('MemberLoginModel');
$memberinfo['memberinfo']=$this->MemberLoginModel->getMember($id);
$this->load->view('member/userprofile',$memberinfo);
}else{
redirect('index.php/HomeController/home');
}
}
public function edit($id){
$data = array(
"action" => base_url('/index.php/MemberLoginController/update/'.$id),
"data" => $this->db->get_where('member',array('id'=>$id))
);
$this->load->view('member/useredit', $data);
}
public function update($id){
$data = array(
'memberfname'=> $this->input->post('memberfname'),
'memberlname'=> $this->input->post('memberlname'),
'email'=>$this->input->post('email'),
);
$this->db->update('member',$data,array('id'=> $id));
redirect('index.php/MemberLoginController/getMember/'.$id);
}
public function getMember(){
$this->load->model('MemberLoginModel');
$memberinfo['memberinfo']=$this->MemberLoginModel->getMember();
$this->load->view('member/userprofile',$memberinfo);
}
public function validate_credentials(){
$this->load->model('MemberLoginModel');
if($this->MemberLoginModel->login()){
echo ("<SCRIPT LANGUAGE = 'JavaScript'>
window.alert('Login Successfully')
window.location.href='userprofile'
</SCRIPT>");
exit();
return true;
}else{
echo ("<SCRIPT LANGUAGE = 'JavaScript'>
window.alert('Invalid username or password. Please click LOGIN again.')
window.location.href='home'
</SCRIPT>");
exit();
//$this->form_validation- >set_message('validate_credentials','Incorrect Email/Password');
return false;
}
}
}
?>
MemberLoginModel.php
<?php class MemberLoginModel extends CI_Model{
public function __construct()
{
parent::__construct();
}
function login()
{
$this->db->where('email',$this->input->post('email'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('member'); /*i added 'member' table on db new members*/
if($query->num_rows()>0)
{
foreach($query->result() as $rows)
{
//add all data to session
$newdata = array(
'id' => $rows->id,
'memberfname' => $rows->memberfname,
'memberlname' => $rows->memberlname,
'email' => $rows->email,
'logged_in' => TRUE
);
}
$this->session->set_userdata($newdata);
return true;
}else{
return false;
}
}
public function add_user()
{
$data = array(
'memberfname'=>$this->input->post('memberfname'),
'memberlname'=>$this->input->post('memberlname'),
'email'=>$this->input->post('email'),
'password'=>md5($this->input->post('password')),
);
$this->db->insert('member',$data);
}
public function getMember()
{
$query=$this->db->get('member');
return $query->result();
}
}
?>
Userprofile.php (view)
<body>
<div class="row rowpadding">
<div class="col-md-3 col-sm-3">
<div class="user-wrapper">
<div class="description">
<img height="200px" width="200px" src="<?php echo base_url();?>upload/no-avatar.jpg">
</div>
<br><br>
</div>
</div>
<div class="col-md-6 col-sm-6 user-wrapper">
<div class="description">
<br>
<h2 class="name">Hi, <?php echo $this->session->userdata('memberfname'); ?>!</h2>
<hr/>
<div class="colwrapper">
<div class="cont-5">
<div class="cont-6 name"><p class="para-2"><span class="font-3">First Name: <?php echo $this->session->userdata('memberfname'); ?>
</span></p></div>
</div><br>
<div class="cont-7">
<div class="cont-8 name"><p class="para-3"><span class="font-4">Last Name: <?php echo $this->session->userdata('memberlname'); ?></span></p></div>
</div><br>
<div class="cont-9">
<div class="cont-10"><p class="para-4"><span class="font-5">Email Address: <?php echo $this->session->userdata('email'); ?></span></p></div>
</div><br>
<div class="cont-11">
<div class="cont-12"><p class="para-5"><span class="font-6"></span></p></div>
</div><br>
</div>
<br><br>
</div>
</div>
<div class="col-md-3 col-sm-3 user-wrapper">
<div class="user-wrapper">
<br>
<div class="description">
<ul class="rightnavi"style="">
<li class="rightnavi">Add Profile Photo</li>
<li class="rightnavi">Update Your Profile</li>
</ul>
<hr/>
</div>
</div>
</div>
<!-- USER PROFILE ROW END-->
</div>
</body>
Useredit.php (View)
<form action="<?php echo $action;?>" method="POST" enctype="multipart/form-data">
<div class="container">
<div class="row rowpadding">
<div class="col-md-3 col-sm-3">
<div class="user-wrapper">
<div class="description">
<img height="200px" width="200px" src="<?php echo base_url();?>upload/no-avatar.jpg">
</div>
<br><br>
</div>
</div>
<div class="col-md-6 col-sm-6 user-wrapper">
<div class="description">
<br>
<h2 class="name">Hi, <?php echo $this->session->userdata('memberfname'); ?>!</h2>
<hr />
<p>
<div class="colwrapper">
<div class="cont-5">
<div class="cont-6 name"><p class="para-2"><span class="font-3">First Name:
<input type="text" name="memberfname" value="<?php echo $this->session->userdata('memberfname'); ?>" required />
</span></p></div>
</div><br>
<div class="cont-7">
<div class="cont-8 name"><p class="para-3"><span class="font-4">Last Name:
<input type="text" name="memberlname" value="<?php echo $this->session->userdata('memberlname'); ?>" required /></span></p></div>
</div><br>
<div class="cont-9">
<div class="cont-10"><p class="para-4"><span class="font-5">Email Address:
<input type="text" name="email" value="<?php echo $this->session->userdata('email'); ?>" required /></span></p></div>
</div><br>
<div class="cont-11">
<div>
<input type="hidden" name="hidden" value="<?php echo $this->session->userdata('id'); ?>"/>
<input type="submit" value="update">
</div>
</div>
<br><br>
</p>
</div>
</div>
</div>
</div>
</div>
</form>
You should combine form_validation object with your code.
public function update($id)
{
if ( (int)$id < 1)//$id is not an integer
{
redirect('memberlogincontroller/home', 'refresh');
}
else
{
$this->load->library('form_validation');//it's good to autoload it
$this->form_validation->set_rules('memberfname', 'First Name', 'trim|required');
$this->form_validation->set_rules('memberlname', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required');
if ($this->validation_form->run() === FALSE)
{
$this->load->view('userprofile');
}
else
{
$data = array(
'memberfname' => $this->input->post('memberfname'),
'memberlname' => $this->input->post('memberlname'),
'email' => $this->input->post('email'),
);
$this->db->update('member',$data,array('id'=> $id));
redirect('memberlogincontroller/getMember/' . $id, 'refresh');
}
}
}
In model you are not passing id of specific member. It should be like this
public function getMember($id)
{
$this->db->where('id', $id);
$query = $this->db->get('member');
if ($query->num_rows() !== 1)
{
return FALSE;
}
return $query->row();//since you need just single member data
}
Also, in controller method code you have to pass $id to model:
public function getMember($id)
{
if (int($id) < 1)
{
redirect('memberlogincontroller/home', 'refresh');//no valid uri segment
}
else
{
$this->load->model('MemberLoginModel');
$memberinfo['memberinfo'] = $this->MemberLoginModel->getMember($id);
if ( ! $memberinfo['memberinfo'])//returned FALSE from model
{
redirect('memberlogincontroller/home', 'refresh');//no $id in DB
}
else
{
$this->load->view('member/userprofile',$memberinfo);
}
}
}
Also, you should pay attention to naming convention. You shouldn't close file with closing php tag. My proposal is to read docs carefully since you could avoid lot of annoying bugs that way.
Redirect should be
redirect('MemberLoginController/members');
redirect('Controller/Method');
If method is not added, So it will call the index() method by default

Codeigniter: not working on displaying form_error with set_value in form_dropdown for validation

I need to display the form_error with set_value in form_dropdown for validation and it didn't work for me.
Here's the model (model_home.php):
public function get_dropdown() {
$result = $this->db->select('designation_id, designation')->get('designation')->result_array();
$dropdown = array();
foreach($result as $r) {
$dropdown[$r['designation_id']] = $r['designation'];
}
return $dropdown;
}
Here's the controller (home.php):
public function viewAddEmployeeForm() {
$this->load->model('Model_home');
$data = array();
$data['dropdown'] = $this->Model_home->get_dropdown();
$this->load->view('imports/header');
$this->load->view('imports/menu');
$this->load->view('emp_add', $data);
}
public function saveEmployee() {
$this->load->model('Model_home');
$data = array();
$data['dropdown'] = $this->Model_home->get_dropdown();
$rules = array(
array('field'=>'emp_desig','label'=>'Designation','rules'=>'trim|required')
);
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == FALSE) {
$this->load->view('emp_add', $data);
} else {
$this->load->model('Model_home');
$p = new Model_home();
$p->designation_id = $this->input->post('emp_desi');
if($p->designation_id == 1) {
$p->user_type = 0;
} else {
$p->user_type = 1;
}
$result = $p->saveEmployee();
if (!$result) {
echo mysqli_error($result);
}
else {
redirect('home/goSettings', 'refresh');
}
}
}
Here's the view (emp_add.php):
<?php echo form_open('home/saveEmployee',array('class'=>'form-horizontal'));?>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Designation <span class="required"><font size="3" color="red">*</font></span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<?php echo form_dropdown('emp_desi', $dropdown, '', 'class="form-control" id="emp_desi" name="emp_desig" value="<?php echo set_value('emp_desig') ?>"'); ?>
<span style="color: red;"><?php echo form_error('emp_desig'); ?></span>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button type="submit" class="btn btn-success" name="emp_submit" id="emp_submit">Submit</button>
</div>
</div>
</form>
How will I display the form_error in form_dropdown especially for set_value? Thanks for your time.
Read the Form Helper doc. Your form_dropdown() was used incorrectly. You should pass in an array of options as the third parameter, rather than use set_value().

Codeigniter Form Validation Doesn't Work and display Error

I have used jQuery datatable for my project.when i add the form validation it display error called "the page at localhost says Error adding/update data. when i run the code without form validations it works fine.i couldn't understand what is the issue with my code.
Controller
class User_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('user_model','user_controller');
$this->load->library('form_validation');
}
public function index()
{
$this->load->helper('url');
$this->load->view('admin_include/header');
$this->load->view('admin_pages/user_view');
}
public function ajax_list()
{
$list = $this->user_controller->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $person) {
$no++;
$row = array();
$row[] = $person->firstname;
$row[] = $person->lastname;
$row[] = $person->gender;
$row[] = $person->address;
$row[] = $person->contact_no;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" title="Edit" onclick="edit_person('."'".$person->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-danger" href="javascript:void()" title="Hapus" onclick="delete_person('."'".$person->id."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->user_controller->count_all(),
"recordsFiltered" => $this->user_controller->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->user_controller->get_by_id($id);
echo json_encode($data);
}
public function ajax_add()
{
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
echo'<div class="alert alert-danger">'.validation_errors().'</div>';
exit;
}
else{
$data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
$insert = $this->user_controller->save($data);
echo json_encode(array("status" => TRUE));
}
}
public function ajax_update()
{
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
echo'<div class="alert alert-danger">'.validation_errors().'</div>';
exit;
}else{
$data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('contact_no'),
);
$this->user_controller->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
}
public function ajax_delete($id)
{
$this->user_controller->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
}
model
class User_model extends CI_Model {
var $table = 'user';
var $column = array('firstname','lastname','gender','address','contact_no');
var $order = array('id' => 'desc');
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column as $item)
{
if($_POST['search']['value'])
($i===0) ? $this->db->like($item, $_POST['search']['value']) : $this->db->or_like($item, $_POST['search']['value']);
$column[$i] = $item;
$i++;
}
if(isset($_POST['order']))
{
$this->db->order_by($column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
}
view
<h3>Client Data</h3>
<br />
<button class="btn btn-success" onclick="add_person()"><i class="glyphicon glyphicon-plus"></i> Add Person</button>
<br />
<br />
<table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Address</th>
<th>Contact No</th>
<th style="width:125px;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Address</th>
<th>Date of Birth</th>
<th>Contact No</th>
</tr>
</tfoot>
</table>
</div>
<script src="<?php echo base_url('assets/jquery/jquery-2.1.4.min.js')?>"></script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>"></script>
<script src="<?php echo base_url('assets/datatables/js/jquery.dataTables.min.js')?>"></script>
<script src="<?php echo base_url('assets/datatables/js/dataTables.bootstrap.js')?>"></script>
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('user_controller/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
function add_person()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
}
function edit_person(id)
{
alert(id);
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('user_controller/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
$('[name="firstname"]').val(data.firstname);
$('[name="lastname"]').val(data.lastname);
$('[name="gender"]').val(data.gender);
$('[name="address"]').val(data.address);
$('[name="contact_no"]').val(data.contact_no);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('user_controller/ajax_add')?>";
}
else
{
url = "<?php echo site_url('user_controller/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function delete_person(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('user_controller/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
}
</script>
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input name="firstname" placeholder="First Name" class="form-control" type="text" >
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Last Name</label>
<div class="col-md-9">
<input name="lastname" placeholder="Last Name" class="form-control" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select name="gender" class="form-control">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<textarea name="address" placeholder="Address"class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input name="dob" placeholder="yyyy-mm-dd" class="form-control" type="text">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
i would prefer HTML 5 validation because its very easy way and HTML 5 validation will check on client side or it will check without refresh the page and codeigniter form validation will refresh the page then show then show error so its a long way...so please use HTML 5 validation

Categories