I want to send a variable '$msg_notf' from my controller to my view but every time I do this, codeigniter returns the error "Undefined variable: msg_notf" .
My Controller,
public function send_message(){
$this->load->model('model_student');
$msg_send=$this->model_student->send_message($this->session->userdata('roll_no'));
if($msg_send==true){
$result['msg_notf']='message sent';
$this->load->helper('url');
redirect('http://localhost/CheckIn_System/index.php/student',$result);
}else{
$result['msg_notf']='unable to send message';
$this->load->helper('url');
redirect('http://localhost/CheckIn_System/index.php/student',$result);
}
}
In view,
echo $msg_notf;
In Controller
public function __construct()
{
parent::__construct();
$this->load->helper('url');//load once Controller load
}
public function send_message()
{
$this->load->model('model_student');
$msg_send=$this->model_student->send_message($this->session->userdata('roll_no'));
if($msg_send==true){
$result['msg_notf']='message sent';
$this->load->view('student',$result);//passing data to view
}else{
$result['msg_notf']='unable to send message';
$this->load->view('student',$result);//passing data to view
}
}
in view
foreach ($msg_notf as $new_msg_notf)
{
echo $new_msg_notf['your_data_field'];//showing your data
}
Your controller may look like this :
public function __construct(){
parent:: __construct();
$this->load->helper('url');
}
public function send_message(){
$this->load->model('model_student');
$msg_send=$this->model_student->send_message($this->session->userdata('roll_no'));
if($msg_send==true){
$result['msg_notf']='message sent';
$this->load->view('path', $result); // path of the
http://localhost/CheckIn_System/index.php/student
}else{
$result['msg_notf']='unable to send message';
$this->load->view('path',$result);
}
}
If you want use redirect, the best idea is use Flashdata. Is a one-time session var that persists until you use it, then is deleted.
you need call: $this->load->library('session');
Declaration:
$this->session->set_flashdata('item', 'value');
To read:
$this->session->flashdata('item');
https://ellislab.com/codeigniter/user-guide/helpers/url_helper.html
The redirect() function does a "header redirect" to the URI specified. The optional second parameter allows you to choose between the "location" method (default) or the "refresh" method.
If you want to pass data into a view use
$this->load->view("View_file", $result);
and on the view page access it like
echo $msg_notf;
With redirect function you should use Session (Userdata or Flashdata)
Flashdata is preferred in this case.
Related
I have this two controller methods that both set session data
//Profile
public function profile()
{
$this->session->set_userdata('title', 'some_value');
}
//KYC
public function kyc()
{
$this->session->set_userdata('title', 'KYC');
$this->load->view('basic/basic_app_views/kyc');
}
I am first loading the function kyc and using the session in my view
<title><?php echo $this->session->userdata('title'); ?></title>
I then load profile in my browser and refresh kyc but the value in kyc is still KYC like i had set in the kyc function.
How come title still has the value KYC even after resetting the value in another controller function?.
It is because each time you call your function it will set the userdata as it defines.
When try to set a title in a page, i suggest you to do this instead.
//Profile
public function profile()
{
$data['title'] = 'Profile Page';
$this->load->view('basic/basic_app_views/kyc', $data);
}
//KYC
public function kyc()
{
$data['title'] = 'KYC Page';
$this->load->view('basic/basic_app_views/kyc', $data);
}
then call it inside your kyc.php file.
<title><?php echo $title; ?></title>
hope that helps.
To see the change in the session title variable you would need to change up your code a little...
So your
//Profile
public function profile()
{
$this->session->set_userdata('title', 'some_value');
}
//KYC
public function kyc()
{
$this->session->set_userdata('title', 'KYC');
$this->load->view('basic/basic_app_views/kyc');
}
To something like...
//Profile
public function profile()
{
$this->session->set_userdata('title', 'some_value');
$this->load->view('basic/basic_app_views/kyc'); // View the title value
}
//KYC
public function kyc()
{
$this->session->set_userdata('title', 'KYC');
$this->load->view('basic/basic_app_views/kyc'); // View the title value
}
That way you will see your value change. Each of your two methods individually change the value. But in your previous code only the kyc was displaying it.
I have a situation of loosing value stored in $member variable.
class User extends CI_Controller {
protected $message;
function list()
{
$data['message'] = $this->message; // it's empty
$this->load->view('view', $data);
}
function delete($id)
{
$this->user_model->delete($id);
$this->message = "Success";
redirect('user/list');
}
}
The reason of using a redirect is to get a clean URL. I get empty value for $this->message in list() after getting redirected.
I even tried making it static, but still no luck.
You could try using flash messages:
function delete($id)
{
$this->user_model->delete($id);
$this->session->set_flashdata('message', 'Success');
redirect('user/list');
}
For this you are likely to need to load session library in constructor of you controller:
$this->load->library('session');
In your view use this:
<?php echo $this->session->flashdata('message');?>
You can preserve data in flash messages for several requests like this:
$this->session->keep_flashdata('message');
Have a look at this link
I've built a simple form validation, I intend to use it for ajax calls but right now I can't seem to get my error messages? I know that the form validator is running and weirder still I can see my error that I want in ci_form_validation->_error_array but this is a protected property :( (this is when I printed the class)
The form validator is working correctly! I've used this method thousands of times before yet I can't seem to get my error messages this time and I have no idea why? I'll keep the code below simple, for testing I've pretty much removed everything.
Ajax controller (parts removed)
<?if(!defined('BASEPATH'))die();
class Ajax extends MY_Controller{
public function __construct(){
//if(!isset($_POST)&&!empty($_POST))redirect('/','refresh');
parent::__construct();
//check this site with requested uri or request server url
$this->con['validation']['add_user']=array(
array('field'=>'firstname','label'=>'First name','rules'=>'max_length[30]|required|alpha'),
array('field'=>'lastname','label'=>'Last name','rules'=>'max_length[30]|required|alpha'),
array('field'=>'email','label'=>'Email address','rules'=>'required|is_unique[users.email]|max_length[150]|valid_email')
);
//$this->html->set_doc_type('html');//set application json
//header('Content-Type: application/json');
}
public function add_user(){
if($this->_fv('add_user')){
$this->load->model('users');
$result=$result=$this->users->insert($this->input->post('firstname'),$this->input->post('lastname'),$this->input->post('email'));
//var_dump('hi there');
echo $result;
}else{
var_dump($this->fv);
var_dump($this->input->post());
var_dump('returned false');
var_dump(validation_errors());
$result=array('firstname'=>form_error('firstname'),'lastname'=>form_error('lastname'),'email'=>form_error('email'));
echo json_encode($result);
}
$this->load->view('index/signup');
//exit;
}
}
My controller
<?if(!defined('BASEPATH'))die();
class MY_Controller extends CI_Controller{
public$con;
public function __construct(){
parent::__construct();
}
public function _fv($form=null){
if($form==null)return true;
$this->load->library('form_validation');
$this->load->library(array('form_validation'=>'fv'));
$this->fv->set_rules($this->con['validation'][$form]);
if($this->fv->run()===false){
return false;
}else{
return true;
}
}
}
Like I said, the weird thing is I can see the error message in the ci_form_validation object but it just doesn't display in form_error() or validation_errors()?
Have I missed an auto loaded library or helper? this is my loaders
$autoload['helper'] = array('url','form');
$autoload['libraries'] = array('HTML'=>'html','database','session');
//HTML is my header and footer building library.
I don't get any PHP errors messages at all. Everything works as it should, I just don't get any error messages? :'(
The error message I want is is_uniqiue.
["_error_array":protected]=> array(1) { ["email"]=> string(52) "The Email address field must contain a unique value." }
I found a solution. My guess is that there's something wrong with my way of working? But I have no idea what. I kind of cheated with my solution but if you have any ideas let me know! :)
<?if(!defined('BASEPATH'))die();
class MY_Form_validation extends CI_Form_validation{
public function __construct(){
parent::__construct();
}
public function get_errors(){
return$this->_error_array;
}
}
I have been developing using non framework for about 3 years and I have heard about PHP framework codeigniter.
I think I missed something using this framework which is used for API for my mobile application.
I've facing some problem to get data from database using Phil's CI framework, RESTful plugin. My browser shows error code:
{"status":false,"error":"Unknown method."}
Using my logic below:
controller: user.php
<?php
require(APPPATH.'libraries/REST_Controller.php');
class User extends REST_Controller{
public function user_get()
{
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
//CHECK TO MODEL FUNCTION
$user = $this->user_model->get_user($this->get('id'));
//IF USER EXIST
if($user)
{
$this->response($user, 200); // 200 being the HTTP response code
}
}
public function user_put()
{
// create a new user and respond with a status/errors
}
public function user_post()
{
// update an existing user and respond with a status/errors
}
public function user_delete()
{
// delete a user and respond with a status/errors
}
}
?>
model: user_model.php
<?php
class User_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_user($id){
$query = $this->db->get('mt_user', array('idmt_user'=>$id));
return $query->row_array();
}
}
?>
i'm accessing the database which is has this rows:
idmt_user,username,password, emails, createdate
accessed using mozilla:
#http://localhost/<project>/index.php/user/<userid>
Where's the error(s) ?
thanks.
update,
i am already defined the autoloads for database. But this problem still persist. Is there any helps? thanks
as stated below in answer, i tried to access the url, /user/get_user/ but still showing the same result. Is there any problem using idmt_user in database?
Insert in controllers:
function __construct() {
parent::__construct();
$this->load->model('user_model');
}
And try this route:
http://localhost//index.php/user/user/id/
I believe that the url you are accessing with is wrong.. Try accessing with the url #http://localhost/<project>/index.php/user/<method_name>/<user_id>
Another way of doing it would be using the URI Class.
Instead of writing the following:
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
Changed to:
$userid = $this->uri->segment(3);
Would be 3 based off the url being http://localhost/<project>/user/<method_name>/<user_id>
Reference for URI Class: http://www.codeigniter.com/user_guide/libraries/uri.html
In order to use $this->get(); there would have to be a query parameter to get. Example: id=
If you are passing query parameters than you could store these values in a array as shown below.
if(!empty($this->get()))
{
$params[] = $this->get();
}
I hope this helps.
You should to try include your model file into your controller file by using a __construct() function, like this:
function __construct(){
parent::__construct();
$this->load->model(array('user_model'));
}
I want to call a function in another controller. for example if user try to log in with incorrect parameter then the application will redirect to another controller and passing a variable (array).
class User extends Controller {
function User()
{
parent::Controller();
}
function doLogin()
{
$userData = $this->users->getAuthUserData($user,$password);
if(empty($userData)){
// this is where i need to call a function from another controller
}else{
echo 'logged in';
}
}
}
is it possible passing a variable using redirect() function in url helper?
Yes you can use redirect('othercontroller/function/'.url_encode($data), 'location');
That should work.
edit: you could also put the code in a helper.
<?php
$array = array('foo'=>'bar', 'baz'=>'fubar', 'bar' => 'fuzz');
$json = json_encode($array);
$encoded_json= urlencode($json);
/* now pass this variable to your URL redirect)
/* on your receiving page:*/
$decoded_json= urldecode($encoded_json);
/* convert JSON string to an array and output it */
print_r(json_decode($decoded_json, true));
?>
this code:
takes an array, converts it to a JSON encoded string.
we then encode the $json string using url_encode. You can pass this via the url.
Decode this URL, then decode the JSON object as an associative array.
might be worth a try
If you want to call a function of one controller from another controller then you can use redirect Helper.
For example:
class Logout extends CI_Controller {
function index() {
session_destroy();
redirect('index.php/home/', 'refresh');
}
}
it will call another contoller.