How to pass Controller method using ajax in codeIgniter - codeigniter

public function index() {
if ($this->session->userdata('admin_login') == 1)
redirect(base_url() . 'index.php?admin/admin_dashboard', 'refresh');
if ($this->session->userdata('teacher_login') == 1)
redirect(base_url() . 'index.php?teacher/teacher_dashboard', 'refresh');
if ($this->session->userdata('student_login') == 1)
redirect(base_url() . 'index.php?student/student_dashboard', 'refresh');
if ($this->session->userdata('parent_login') == 1)
redirect(base_url() . 'index.php?parents/parents_dashboard', 'refresh');
$this->load->view('backend/login');
}
function ajax_login() {
$response = array();
$email = $_POST["email"];
$password = sha1($_POST["password"]);
$response['submitted_data'] = $_POST;
$login_status = $this->validate_login($email, $password);
$response['login_status'] = $login_status;
if ($login_status == 'success') {
$response['redirect_url'] = '';
}
echo json_encode($response);
}
I want to pass index() through $response['redirect_url'] = ''; how to pass? i already tried by creating routes but not working.

index() is a function, which according to your code either redirects the user or shows a page. Neither are good for an ajax response as the redirection or view will only occur or render in the ajax request not the users viewport.
I assume you want to add the logic in your index function without repeating yourself too much. Simple solution is to make a function for redirect.
Create a helper and put this function in it:
function group_redirect() {
$ci = &get_instance();
$ci->load->helper('url');
if ($ci->session->userdata('admin_login') == 1)
return base_url() . 'index.php?admin/admin_dashboard';
if ($ci->session->userdata('teacher_login') == 1)
return base_url() . 'index.php?teacher/teacher_dashboard';
if ($ci->session->userdata('student_login') == 1)
return base_url() . 'index.php?student/student_dashboard';
if ($ci->session->userdata('parent_login') == 1)
return base_url() . 'index.php?parents/parents_dashboard';
return false;
}
Then the rest is easy:
public function __construct() {
$this->load->helper('name_of_helper_with_function');
}
public function index() {
$redir = group_redirect();
if ($redir) {
redirect($redir);
}
$this->load->view('backend/login');
}
function ajax_login() {
$response = array();
$email = $_POST["email"];
$password = sha1($_POST["password"]);
$response['submitted_data'] = $_POST;
$login_status = $this->validate_login($email, $password);
$response['login_status'] = $login_status;
if ($login_status == 'success') {
$response['redirect_url'] = $redir;
}
echo json_encode($response);
}

Related

How to redirect to another page in codeigniter from one page?

I have written a code in the controller which is given below. This code is for login page. In this code, the if statement notification is properly working but the else part is not working. It is not redirect to the url given in the redirect() instead it is showing a blank page. Can anyone tell y it is like that and correct it for me ? I have used header() function but also it is not working.I have placed all the code inside the 'kw' folder. This code is properly working in the localhost but when uploaded the same code to the live server, its not working.Is it due to version of the CI ?
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->library('validation');
$this->load->model('studentsmodel');
}
public function index() {
if (isset($_POST['submit']))
{
$post_data = array('stud_cin' => $this->input->post('stud_cin'),'stud_password' => $this->input->post('stud_password'),
);
$this->validation->set_data($post_data);
$this->validation->set_rules('stud_cin','Cin','required|trim');
$this->validation->set_rules('stud_password','Password','required|trim');
if ($this->validation->run() === FALSE)
{
}
else
{
$this->load->model("studentsmodel");
$this->load->helper('url');
$result = $this->studentsmodel->loginCheck($post_data);
if (!$result){
$this->notifications->notify('Wrong username/password; Login Failed','error');
}
else{
$this->session->set_userdata('student_id', $result['id']);
$this->session->set_userdata('stud_cin', $result['stud_cin']);
$this->session->set_userdata('stud_photopath', $result['stud_photopath']);
redirect('student/profile/edit/id/'.$this->session->userdata('student_id'),'refresh');
//header('location:http://www.website.com/kw/application/controller/student/profile/edit/id/$this->session->userdata("student_id")');
}
}
} $this->load->view("login");
}
}
profile controller edit function
public function index()
{
$student_id=$this->session->userdata('student_id');
$data['profile_data'] =$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profileDetails.php", $data);
}
public function edit()
{
$uri = $this->uri->uri_to_assoc(4);
$student_id=$uri['id'];
if(isset($_POST['btn_submit']))
{
//echo "<pre>";print_r($_FILES);exit;
$img_val = $this->studentsmodel->getStudent_photo($student_id);
$photo_val = $img_val['stud_photopath'];
$photo_unlink = "";
if ($_FILES['stud_photopath']['name'] != "")
{
/*echo "in";exit;*/
$photo_chk = explode("photo/", $photo_val);
$photo_unlink = $photo_chk[1];
$photo_path = "";
$flag = "";
$f_type_chk = $_FILES['stud_photopath']['type'];
if ($f_type_chk != "image/gif" && $f_type_chk != "image/jpg" && $f_type_chk != "image/jpeg"
&& $f_type_chk != "image/bmp" && $f_type_chk != "image/png" && $f_type_chk != "")
{
$flag = "Select allowed file type and size for photo";
}
if ($_FILES['stud_photopath']['size'] >= 5242880) { $flag = "Select allowed file type and size for photo"; }
$target_path = getcwd() . "/public/photo/";
$db_path = "photo/";
if ($_FILES['stud_photopath']['name'] != '')
{
$file_name = $_FILES["stud_photopath"]["name"];
$file_size = $_FILES["stud_photopath"]["size"] / 1024;
$file_type = $_FILES["stud_photopath"]["type"];
$file_tmp_name = $_FILES["stud_photopath"]["tmp_name"];
$random = rand(111, 999);
$new_file_name = $random . $file_name;
$newfile_name=$cin."_". $file_name;
$upload_path = $target_path . $newfile_name;;
if (move_uploaded_file($file_tmp_name, $upload_path)) { $photo_path = addslashes($db_path . $newfile_name); } /*end if*/
else { $this->notifications->notify('Photo cannot upload', 'error'); }/*end else var_dump($this->validation->show_errors());*/
}/*end if $_FILES['photo']['name']*/
} /*END OF if ($_FILES['photo']['name'] != "") */
else { $photo_path = $photo_val; } /*END OF ELSE ($_FILES['photo']['name'] != "") */
$this->session->unset_userdata('stud_photopath');
$this->session->set_userdata('stud_photopath', $photo_path);
$data['photo_unlink'] = $photo_unlink;
/* echo $dob_dd = $this->input->post('dob_dd');exit;
$dob_mm = $this->input->post('dob_mm');
$dob_yy = $this->input->post('dob_yy');
$dob = $dob_dd . "-" . $dob_mm . "-" . $dob_yy;*/
$stud_age_dob =$this->input->post('stud_age_dob');
$timestamp = strtotime($stud_age_dob);
$dob = date('Y-m-d', $timestamp);
$validation_data = array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' =>$this->input->post('stud_age_dob'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
);
//echo "<pre>";print_r($validation_data); exit;
$this->validation->set_data($validation_data);
$this->validation->set_rules('stud_name', 'Student Name', 'trim|alpha_space|required');
$this->validation->set_rules('stud_gender', 'Gender', 'required');
$this->validation->set_rules('stud_age_dob', 'DOB', 'required');
$this->validation->set_rules('stud_mobile', 'Mobile number', 'numeric|required');
$this->validation->set_rules('stud_email', 'Email Id', 'trim|required|valid_email|xss_clean');
if ($this->validation->run() === FALSE)
{ /* var_dump($this->validation->show_errors()); */ $this->notifications->notify('Please make all entries', 'error');}
else
{
$updation_data=array(
'stud_name' => $this->input->post('stud_name'),
'stud_gender' => $this->input->post('stud_gender'),
'stud_age_dob' => $this->input->post('stud_age_dob'),
'stud_gaurdian' =>$this->input->post('stud_gaurdian'),
'stud_mother' =>$this->input->post('stud_mother'),
'stud_mobile' => $this->input->post('stud_mobile'),
'stud_email' => $this->input->post('stud_email'),
'stud_tel' => $this->input->post('stud_tel'),
'stud_guardian_address' => $this->input->post('stud_guardian_address'),
'stud_pin' => $this->input->post('stud_pin'),
'stud_photopath' => $photo_path,
'stud_age_dob' => $dob
);
/*echo "<pre>";print_r($updation_data); exit; */
$update_status=$this->studentsmodel->update_profile($updation_data, $student_id);
if($update_status==1)
{
//$this->session->set_userdata('profile_status', 'Yes');
/*$this->session->userdata('profile_status');*/
redirect('student/profile/index/', 'refresh');
}
else
{
$this->notifications->notify('profile updted failed', 'error');
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$_POST;
}
$data['profile_data']=$this->studentsmodel->get_Cinprofile($student_id);
$this->load->view("profile_edit.php",$data);
}
Check if you already load this helper
$this->load->helper('url');
This is the information about the redirect function
redirect($uri = '', $method = 'auto', $code = NULL);
Parameters:
$uri (string) URI string $method (string)
Redirect method (‘auto’,
‘location’ or ‘refresh’)
$code (string) HTTP Response code (usually 302 or 303)
Note:
Don't forget add in the config file the value for base_uri
https://www.codeigniter.com/user_guide/helpers/url_helper.html
https://www.codeigniter.com/userguide3/libraries/config.html
remove /id/ from your redirect()
redirect('student/profile/edit/'.$this->session->userdata('student_id'));

How to pass a message from model to controller codeigniter?

I want to pass a message variable in some conditions to controller from model in codeigniter. But when i am doing this it is printing only "No" everytime.
Model is
public function add_city() {
/* Storing form data into an array */
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
And Controller is
public function addingCity() {
$this->add_model->add_city();
var_dump($msg);
//redirect("/city");
}
Try This also
public function add_city() {
$data = array(
'city_name' => $this->input->post('city'),
'city_overview' => $this->input->post('overview')
);
/* Checking if already exist in database */
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='" . $data['city_name'] . "' ORDER BY id ASC");
$count_row = $query->num_rows();
if ($count_row > 0) {
$msg = "No";
} else {
$this->db->insert('city_tbl', $data);
$msg = "Yes";
}
return $msg;
}
On controller redirect message with get method -
public function addingCity() {
$msg = $this->add_model->add_city();
redirect("/city?msg=".$msg);
}
And finally print this message on view page
echo $this->input->get('msg');
You need to assign value to $msg in your controller
public function addingCity() {
$msg=$this->add_model->add_city();// assign
var_dump($msg);
//redirect("/city");
}
Try this
public function add_city() {
$city_name = $this->input->post('city');
$city_overview = $this->input->post('overview');
$query = $this->db->query("SELECT * FROM city_tbl WHERE city_name='$city_name' ORDER BY id ASC");
$result = $query->result_array()
$count = count($result);
if(empty($count))
{
$msg = "No";
return $msg;
}
else{
$data = array(
'city_name'=>$this->input->post('city'),
'city_overview'=>$this->input->post('overview') );
$this->db->insert('city_tbl', $data);
$msg = "Yes";
return $msg;
}
}
In Controller
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;
}
To pass data to view
public function addingCity() {
$data['msg'] = $this->add_model->add_city();
$this->load->view("filename", $data); # ex $this->load->view("index", $data);
}
Error is in your controller function
Try with this code
public function addingCity() {
$msg = $this->add_model->add_city();
echo $msg;die;
//redirect("/city");
}

$this->form_validation->run() not executing

I have an issue in codeignitor form handling it does not execute $this->form_validation->run() on local server. But it does work very fine on live server. I can't find out what is the reason. Here is my controller.
class Login extends CI_Controller
{
function __construct(){
parent::__construct();
}
function removeUser($record_id){
$a = new Alumni();
$a->removeConnections($record_id);
}
function index(){
$redir = isset($_GET['redir'])?$_GET['redir']:'admin';
if ($this->tank_auth->is_logged_in()) { // logged in
redirect('admin');
} elseif ($this->tank_auth->is_logged_in(FALSE)) { // logged in, not activated
redirect('/login/send_again/');
} else {
//
$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
$this->config->item('use_username', 'tank_auth'));
$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
$this->form_validation->set_rules('remember', 'Remember me', 'integer');
// Get login for counting attempts to login
if ($this->config->item('login_count_attempts', 'tank_auth') AND
($login = $this->input->post('login'))) {
$login = $this->security->xss_clean($login);
//var_dump($login);
} else {
$login = '';
}
//var_dump($this->input->post("remember"));
$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
if ($data['use_recaptcha'])
$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
else
$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
}
$data['errors'] = array();
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
if ($this->form_validation->run() === false) {
}else{
echo " logged in";// validation ok
$loginID = $this->input->post("login");
$pass = $this->input->post("password");
$remember = $this->input->post("remember");
//echo $loginID;
if ($this->tank_auth->login(
$loginID,
$pass,
$remember,
$data['login_by_username'],
$data['login_by_email'])) { // success
echo "success";
redirect($redir);
} else {
$errors = $this->tank_auth->get_error_message();
//echo "error";
if (isset($errors['banned'])) { // banned user
$this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);
} elseif (isset($errors['not_activated'])) { // not activated user
redirect('/auth/send_again/');
} else { // fail
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
}
}
.....
Sorry for long code please help me.
I don't see the library getting loaded in your constructor
public function __construct()
{
parent :: __construct();
$this->load->helper('url');
$this->load->helper('cookie');
//load the validation library
$this->load->library('form_validation');
$this->load->library("pagination");
}

codeinighter where field = data from form

I'm trying to match up suppliers from a postcode search:
Model code:
function get_suppliers(){
$this->db->from('suppliers');
$this->db->where('postcode', $data);
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
Controller code:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
echo("postcode entered");
$data['rows'] = $this->site_model->get_suppliers($data);
print_r($data);
}
}
Obviously ignore the printers and echo thats just me bring to see whats going on I'm pretty sure i need to just change the $data in model to something just not sure what(tried heaps of things)
Model:
function get_suppliers($postcode = '*') // <-- Capture the postcode
{
$this->db->from('suppliers');
$this->db->where('postcode', $postcode); // <-- pass it in here
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Controller:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
$data['rows'] = $this->site_model->get_suppliers( $data['postcode'] ); // <-- pass the postcode
echo("postcode entered: " . $data['postcode'] . "<pre>");
print_r($data);
}
}
In your model:
function get_suppliers($data = ''){
i.e.: You haven't included $data as the argument

codeigniter 404_override

I have set the $routes['404_override'] = 'city/switch_site'
now in my city controller
class City extends CI_Controller {
function __construct() {
parent::__construct();
}
function switch_site( ) {
$this->load->helper('url'); // load the helper first
$city = $this->uri->segment(1);
$segment_cnt = 1;
$valid_url = '';
switch( $city ) {
case 'pune':
$segments = $this->uri->segment_array(2);
foreach($segments as $value) {
if($segment_cnt > 1) {
$valid_url .= $this->uri->slash_segment($segment_cnt);
}
$segment_cnt++;
}
$this->config->set_item('cityid',1);
$this->config->set_item('cityname','pune');
echo APPPATH.'controllers/'.$valid_url;
include_once(APPPATH.'controllers/'.$valid_url);
break;
case 'mumbai':
$segments = $this->uri->segment_array(2);
foreach($segments as $value) {
if($segment_cnt > 1) {
$valid_url .= $this->uri->slash_segment($segment_cnt);
}
$segment_cnt++;
}
$this->config->set_item('cityid',2);
$this->config->set_item('cityname','mumbai');
include_once(APPPATH.'controllers/'.$valid_url);
break;
default:
}
}
}
how do i now pass the correct url to codeigniter router
I think you are going about this all wrong. Inside your switch instead of including other controllers which will not work use the redirect() to take them where they should go.

Resources