codeigniter data passing controller->library->view - php

I have a codeigniter problem. Im trying to send data from a controller , to a library , to a view.
i get this error in the view:
Message: Undefined variable: crimes
FileName: views/crime_view.php
Line: 45
while debugging , i dump the $data variable, and get:
that shows that my variables exist.
in the library , im getting the controller data by using:
$data[] = $componentData;
that would not work in this case. but if i in the library do:
$data['crimes'] = "test";
then it will work. for some reason it wont process the incomming arrays from the controller.
how can i get this to work?
full code:
function renderComponent($componentData = array())
{
$data[] = $componentData; // stores controller variables.
$data['rankDetails'] = $this->CI->user->rank_for_xp($userId);
var_dump($data);
$this->CI->load->view('components/crime/views/crime_view', $data);
}
example from the controller:
Q: How can i fix this to get it passing the variables needed? so i acually can get to use the $wait variable in the view?

You have a two dimensional array.
I think somewhere $data[] = ... must be $data = ...
to debug your arrays you could do like this:
echo '<pre>';
print_r($data);
echo '</pre>';
This shows clearly that your array is in another array...

Related

How to get json data in blade laravel

In the blade template:
<?php
$meta = json_encode($datas,true);
echo $meta;
?>
It shows:
{"data":[{"id":1,"title":"Alice.","rating":0},
{"id":2,"title":"So Alice.","rating":2},
{"id":3,"title":"Alice.","rating":2},
{"id":4,"title":"After a.","rating":2},
{"id":5,"title":"Alice.","rating":0}],
"meta":{"song_count":5}}
My question is how to get (song_count: 5 ) in blade template.
I have tried :
echo $meta['meta'];
"
it shows;
"Illegal string offset 'meta'"
Anyone can help, thank you so much
json_encode() method give you a json formatted data. You meed to decode it :
$meta = json_encode($datas,true);
$meta = json_decode($meta, true);
echo $meta;
Now you acess the array property as $meta['meta'];
NB : if $datas is already an array, then you don't need to encode and decode
thats mean you try to take meta key from string because $meta is json not array so you dont need to json_encode $data , you can do direct :-
$datas['meta']['song_count'] if $data is array . but this maybe give you error if $datas is empty to solve this you can make check if $data !empty or use optional method in laravel like this :- optional($datas['meta'])['song_count'] it solve the problem .
The steps to show the value of json data from controller as bwlow:
<?php
$datas = json_encode($datas,true);
//dd($data);
$datas = json_decode($datas);
// dd($datas);
foreach($datas->meta as $link){
echo $link;
}
?>

Passing value from controller to view

I have a query in my model using joins and returned the query results as array
result_array();
I then returned that result to my controller where i called the model.
$data = $this->Model->show();
foreach($data as $val)
{
$arr[$val['recipename']] = $val['componentname'];
}
if($data != null)
{
$this->load->view('Admin\success',$arr);
}
I didnt originally had $arr value. I just added it up there to make the array clearer. Anyhow, with or without.
var_dump($data) and var_dump($arr) or even if i $recipename or $componentname stll null.
returns null. says they are undefined.
I don't know what went wrong.
I read this other question. that is why i made the $arr so i could make it a single array and so when it transfers it will be extracted and tried to echo them but to no avail.
Codeigniter passing data from controller to view
EDIT:
query works fine, it returns values.
$sample = $this->db->select('recipe.recipename,component.componentname')->from('recipe')
->join('recipecomponent','recipe.recipeid = recipecomponent.recipeid')
->join('component','component.componentid = recipecomponent.componentid')
->group_by('recipe.recipeid')
->get()
->result_array();
return $sample;
Once you pass an array of data to your view the array keys are turned into variables. Say for example after your foreach loop your $arr variable is an array like this
array [
'cheese' => 'brie'
'cookie' => 'chocolate chips'
]
You would then access $arr['cheese'] by doing the following in the view
echo $cheese;
Trying to access $data or $arr in the view won't work because they are not in scope
$data is most likely empty and you are iterating an empty array.
A simple way to debug is found below:
Debugging an array or object:
echo '<div style="padding:15px; background-color:white;"><pre>'.print_r($data, true).'</pre></div>';
or
echo '<div style="padding:15px; background-color:white;"><pre>'.print_r($this->Model->show(), true).'</pre></div>';
You should also turn on error reporting in your __construct like so:
error_reporting(E_ALL);
If the print_r() shows you an empty array then your model is returning no data and the answer to your question is probably that you need to fix your query.

Controller to view passing an array

So I have this line of code in my controller:
$this->load->view('sampleview',$result);
So when I go into my view and try to echo result, either by foreach or directly writing
print_r($result);
it shows an error that it is an undefined variable.
But when I put the print_r($result); on my controller like this below:
function show()
{
$this->load->view('sampleview',$result);
print_r($result);
}
It would print on my sampleview page where I was redirected. I’m confused why this is happening.
EDIT
The whole controller would be: I have another view which I click an anchor tag with segment(3) as an id. Then I query that id to my model then pass it to another view for display.
$id = $this->uri->segment(3);
$result = $this->model->show($recipe_id);
if($result!=null)
{
$this->load->view('Admin_recipe_edit',$result);
}
You $result array will be extracted in your view. if you want as an array, then do it as
$data["result"] = $result;
$this->load->view('sampleview',$data);
Then do print_r($result); in view.
This is how you should have to make a array of data that you want to access on your view
// Your array
$result['Data_Array'] = array(....);
$this->load->view('sampleview',$result);
print_r($result);
Now Access like this in your View Section:
View
print_r($Data_Array);
Dude try to put $result in an array example$view_data['$result']=$result; then load the view exmaple $this->load->view(your_view,$view_data);. and in the view page try to print $result.exmaple print_r($result); .It will work I think so.
In CodeIgniter
$Data['result'] = $ArrayData;
$this->load->view('viewfile',$Data);
In View
print_r($result);

How to set an array in session in codeigniter?

I am little bit struggling in setting array in session.
Here is my code:-
Controller:
function taketest(){
$this->load->model('', '');
$questions_for_test = $this->session->userdata('questions_for_test');
$difficulty_level = $this->session->userdata('difficulty_level');
$question_id = $this->session->userdata('question_id');
if($question_id==""){
$question_id = $this->myjcat->returnRandomQuestion($questions_for_test,$difficulty_level);
$this->session->set_userdata('question_id',$question_id);
}
$question_details = $this->myjcat->getQuestion($question_id);
}
Model:
function returnRandomQuestion($questions_for_test, $difficulty_level){
$question_id = array_rand($questions_for_test[$difficulty_level], 1);
$used_question=array();
$used_questions=$questions_for_test[$difficulty_level][$question_id];
$this->session->set_userdata('used_questions',$used_questions);
return $questions_for_test[$difficulty_level][$question_id];
}
But when I call:
$used_questions = $this->session->userdata('used_questions');
in controller
in the controller it will not return me an array.It gives me last value stored in it.
I could be misreading things, but it looks like you are only storing one value.
// this code:
$used_questions=$questions_for_test[$difficulty_level][$question_id];
$this->session->set_userdata('used_questions',$used_questions);
// is the same as this code
$this->session->set_userdata('used_questions',$questions_for_test[$difficulty_level][$question_id]);
You're probably looking for this:
// fetch the stored copy first.
$used_questions = $this->session->userdata('used_questions');
if(!is_array($used_questions)) $used_questions = array();
// note the []
$used_questions[] = $questions_for_test[$difficulty_level][$question_id];
$this->session->set_userdata('used_questions',$used_questions);
You can set array values in session data like this :-
$this->session->set_userdata('used_questions', json_encode($used_questions));
And retrieve the data as :-
json_decode($this->session->userdata('used_questions'));
If you want the retrieved array data as associative array :-
json_decode($this->session->userdata('used_questions'), true);
Hope it hepls you :)
The problem is that $used_questions is storing the value stored in $questions_for_test[$difficulty_level][$question_id] and not the array.
So do this $this->session->set_userdata('used_questions',$questions_for_test);
This is because the data you pass to the $used_questions is a value.
You might want to do something like this:
array_push($used_questions, $questions_for_test[$difficulty_level][$question_id]);
*appending / adding a new value to an array

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

Categories