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.
Related
I want to pass $data from the controller named poll to the results_view however I am getting an undefined variable error.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Poll extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('form');
}
public function index()
{
$this->load->view('poll_view',$data);
}
public function vote()
{
echo "Voting Successfull";
$this->db->insert('votes',$_POST);
}
public function results()
{
echo "These are the results";
//$query = $this->db->get('votes');
$data = "hello";
$this->load->view('results_view', $data);
}
}
Results_view.php
<html>
<?php echo $data; ?>
</html>
$data should be an array or an object: http://codeigniter.com/user_guide/general/views.html
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('results_view', $data);
results_view.php
<html>
<?php
//Access them like so
echo $title.$heading.$message; ?>
</html>
In simple terms,
$data['a'] in controller becomes $a in your view. ($data won't exist in your view, only the index will become available)
e.g.
Controller:
$data['hello']='hellow world';
view:
echo $hello;
You just need to create a array, you using codeigniter right?
Example on controller:
$data['hello'] = "Hello, world";
$this->load->view('results_view', $data);
In de page "results_view" you just have to:
<?php echo $hello;?>
Obs: You can create n datas, just pay attention in the name and make it a array.
ObsĀ²: To use the data use the key of the array with a echo.
The view wouldn't call the data 'data'
The controller would include an associative index (not sure if that's correct nomenclature) for data e.g 'stuff' looking thus $data['stuff']
You'd echo in the view so: echo $stuff; not echo $data;
I am a v lowly code fiddler but do really like CodeIgniter so excuse me if i've got this arse about tit.
One more thing - surely your constructor function is a bit of a waste. All that loading of libraries and helpers is done with the autoload file.
You can create property $data = []; inside CI_Controller(path: system/core/Controller.php) and store all data to show in view. U can load common data like languages, menu, etc in CI_Controller. Also u can add special data for view in controller. (example: $this->data['message'] = "Hello world";)
Finally, u can pass $this->data to view when load view (example: $this->load->view('view_name',$this->data);)
I hope this will help you
you can do it this way
defined array in controller
$data['hello'] = "hello";
and pass variable to view
echo $hello;
If you pass
$data = your code
$this->load->view('your-page', $data);
and get data on your view as
<?php echo $data;?>
It won't work because ci didn't understand this patern. If like to pass value form controller to view so you can try this -
controller -
$data['any-name'] = your values;
$this->load->view('your-page', $data);
then in your view you can get this data by -
<?php echo $any-name;?>
Hope this helps you.
In your controller you can pass
$data['poll'] = "Your results";
In your view you can call
echo $poll;
In controller:
$data["result"] = $this->login_model->get_login(); // Get array value from DB..
$this->load->view('login-form',$data); // Pass the array to view
In view:
print_r($result); // print the array in view file
Ok so I finally solved it. You should really have a model (it helps a lot)
In your model do something like
Model
class poll_model extends CI_MODEL {
function __construct() {
$this-load->database();
}
function get_poll {
$this->db->query("SELECT * FROM table");
$row = $query->row();
$obj = array(
'id' => $row->id
);
return $obj;
}
}
Now if you have more than an id say name of poll # you can add in array.
Now in your controller do
class Poll extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('form');
$this->load->model('poll_model');
}
public function index()
{
$data["a"] = $this->poll_model->get_poll();
$this->load->view('poll_view',$data);
}
And finally in VIEW put
<? echo $a["id"]; ?>
This is a big help. I figured it out by testing and it works for me.
I have seen all above answer so here is what I do when I have to load the data from the controller to my view.
To Pass the Data To the view from the controller:
public function your_controller(){
// Your Necessary Code
// You have the $data, $data2, $data3 to post to the view.
$this->load->view('your_view_directory or view_page',['data'=>$data, 'data2'=>$data2, 'data3'=>$data3... so on ]);
}
And At the View Side You can simply retrieve that data:
To Display You can simply use echo, print, print_r. And if you want to loop over it, you can do that as well.
In controller:
public function product(){
$data = array("title" => "Books", "status"=>"Read","author":"arshad","company":"3esofttech",
"subject":"computer science");
Data From Model to controller
$this->load->model('bookModel');
$result = $this->bookModel->getMoreDetailsOfBook();
**Add *$result* from model to *$data* array**
$data['tableRows'] = $result;
$data from Controller to View
$this->load->view('admin/head',$data);
And to access in view file
views/user.php
<?php echo $data;
foreach($tableRows as $row){ echo
$row['startData']; } ?>
Instead of
$data = "hello";
$this->load->view('results_view', $data);
Do
$data['hello'] = 'hello';
$this->load->view('results_view', $data);
In your controller file and controller will send data having hello as string to results_view and in your view file you can simply access by
echo $hello;
I am new to CodeIgniter. I am trying to read values from query string in conventional method not segment.
This is my url.
http://localhost/Voyager/Main/UserActivation/?u=6df497644a10241cd89fad80f5c98496
Controller:
class Main extends CI_Controller{
public function UserActivation()
{
$hash=$this->input->get('u', TRUE);
log_message('debug', $hash, false);
$this->load->view('Main\view_userActivation');
}
}
I am trying to read value of 'u' in controller. But this isn't working. I am getting empty value in $hash variable.
Any help is appreciated.
Codeigniter works with URI Segments. You pass the values straight in your URL, separated with / and you grab them with positions after base_url like
$this->uri->segment(3)
Check this link: Codeigniter Documentation
There's a config option that unsets the $_GET array, but only if you have decided to change it.
This is how it looks by default in application/config/config.php:
$config['allow_get_array'] = TRUE;
If you've changed it to false - switch it back to true. Other than that, there's no reason why this wouldn't work, by default.
you can do something like this
Method 01
class Main extends CI_Controller{
public function UserActivation($u)
{
echo $u;
die;
$this->load->view('Main\view_userActivation');
}
}
Then URL should be
http://localhost/Voyager/Main/UserActivation/6df497644a10241cd89fad80f5c98496
Method 02
class Main extends CI_Controller{
public function UserActivation()
{
$value = $this->uri->segment(3);
echo $value;
$this->load->view('Main\view_userActivation');
}
}
Remove the / from the last uri segment.
http://localhost/Voyager/Main/UserActivation?u=6df497644a10241cd89fad80f5c98496
Also, another thing. Why you have your uri controller and methods starting in uppercase? That shouldn't be that way.
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 have an html with a script that is like so (btw, HAVe to use old fashioned post in my html for reasons)...
#extends('layout')
// ... includes for jquery and ajax
<script>
var theVariableINeedInLaravel = "SomeInterestingStringI'mSure"; // in reality, this is a stringify.
$.post ("foo", function(theVariableINeedInLaravel) {
}
</script>
#stop
Then in routes.php...
<?php
Route::post('foo', 'ThatOneController#getValue');
?>
Then, in the related controller....
ThatOneController.php
class ThatOneController extends \BaseController{
public function getValue(){
error_log(print_r($_POST,true)); // returns nothing.
error_log(print_r(input::all()); // returns nothing.
}
}
Or, an alternate version of the function...
public function getValue(Request $request){
error_log(print_r($request->all()); // returns nothing.
}
None of them seem to work. How can I get my post variable?
try this
use Request;
class ThatOneController extends \BaseController{
public function getValue(){
print_r(Request::all());
}
Turns out that even if $_post isn't always accessible from inside a controller function, it is directly accessible from Routes. It's a bit hacky, and "not the laravel way" but you can use $_post in routes to get and pass into other variables to get back into the normal flow.
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.