I want to pass a language id for each link i click from my view to controller.
My view code is
<?php foreach ($languages as $lang) { ?>
<li>
</li>
<?php } ?>
My controller is
public function box($box_id=null, $language_name=null, $language_id=null) {
/// my function code
echo $box_id;
echo $language_name;
echo $language_id;
$data['languages'] = $this->Home_model->getLanguages($box_id);
}
The languages array contain the language id and language name
i want the name to be in url but not the id
The url looks like this
http://localhost/mediabox/home/box/12/en
if i send the language id in url it is then visible otherwise it is not visible in the controller.
How can I get language id for each link in controller without sending it in url
Thanks
pass the language name in the url without the ID, compare to languag_name column in table.
Lets assume you have url: http://localhost/mediabox/home/box/en
controller
<?php
# I wont write a controller but you should know how to do that, im also writing code as if you are just focusing on getting language.
public function box( /**pass in your other uri params as needed **/ $lang_name = 'en'){
#you could load this in the constructor so you dont have to load it each time, or in autoload.php if your using it site wide.
$this->load->model('lang_model', 'langModel');
#this example shows loading the library and running the function
$this->load->library('lang_library');
$this->lang_library->_getLang($lang);
#this example shows putting the getLang function inside the controller itsself.
self::_getLang($lang);
}
library/private function
<?php
private functon _getLang($lang = 'en'){
#run the query to retrieve the lang based on the lang_name, returns object of lang incl id
$lang = $this->langModel->getLang($lang_name);
if (!$lang){
die('language not found');
}else{
return $lang;
}
lang model
<?php
public function getLang($lang_name = 'en'){
$this->db->where('lang_name', $lang_name);
$this->db->limit(1);
$q = $this->db->get('languages');
if ($q->mysql_num_rows > 0){
return $q->result();
}else{
return false;
}
}
you will then have a variable with object associated to it then you can simply call $lang->lang_name; or $lang->lang_id;
Session storage
<?php
#you could call this in the beginning after using an ajax `$.post();` to retrieve the ID.. the easiest route though is whats above. I use this in my REST APIs
$this->session->set_userdata('lang', $lang);
Your confusion is in 'passing back' to the controller. Don't think of it as from controller => View (passing it say $data['something'] variables).
Its basically a <form>, so take a look at form helper and then at form validation.
That will give you an idea of how to create a form using codeigniter syntax.
In your controller, you would do a validation, and if it matches the language (or whatever you submit), then you can utilize sessions to save it for every page (so you don't need it in the URL).
Sessions are very simple and saving an item is as easy as:
$this->session->set_userdata('varname', 'value');
Later, on every other controller, you can check the variable
$language = $this->session->userdata('varname');
// load language etc;
Make a table with language ID and Language name in the database, just pass the language name to the controller and get the language ID by doing a db call.
You could do it using jQuery. Something like;
In View;
<ul id="language_selector">
<?php foreach ($languages as $lang) { ?>
<li>
<a href="javascript:;" class="change-language" data-language="<?php echo $lang['language_name']?>" data-box="<?php echo $template_data['box_id']?>">
<img src="<?php echo base_url(); ?>public/default/version01/images/country_<?php echo $lang['language_name'] ?>.png" width="27" height="18" border="0" />
</a>
</li>
<?php } ?>
</ul>
The JS;
$(function() {
$('.change-language').live('click', function() {
var language_name = $(this).data('language');
var box_id = $(this).data('box');
$.ajax({
url: '/home/box/'+language_name,
type: 'post',
data: 'box_id='+box_id,
success: function( data ) {
self.parent.location.reload();
},
error: function( data ) {
alert('oops, try again');
}
});
});
});
The controller:
public function box($language) {
$box_id = $this->input->post('box_id');
// do a llokup on the language as suggested by #vivek
}
You are telling CodeIgniter that you will be receiving both the language name and id in your action.
public function box($box_id=null, $language_name=null, $language_id=null) {
}
Change that to just
public function box($box_id=null, $language_name=null) {
}
For your example URL you should then get $box_id == 12 and $language_name == 'en'.
Then lookup the language id by using it's name either in a helper or as part of a Language model as Mike suggests.
Related
I am Trying To Reload Contents Of Page. Through link button Filter In PHP
By Passing Some Value Through Query String To Controller Method.
The Controller Method Loads The Same Page From Where I am Passing Query String.
But The View Is Not Reloading.
But If I Call The Controller Method Some Other View It Works Fine.
here is my code
mainview.php
English
maincontroller.php
Here Is The Index Method Of Controller.
$movielanguage=$this->input->get('language');
if(!empty($movielanguage))
{
$moviedata['popularmovies']=$this->main_model-
>getmoviebylanguage($movielanguage);
}
$moviedata['allmovies']=$this->main_model->getAllMovies();
$this->load->view('home/mainview.php',$moviedata);
}
Here View Does Not Refresh Its Contents
How Can I Solve This
Hope this will help you :
First if you want a single view ,should put you code it in if else condition and second assign your data in same variable
Your code should be like this :
public function index()
{
$movielanguage=$this->input->get('language');
if(! empty($movielanguage))
{
$moviedata['movies']=$this->main_model->getmoviebylanguage($movielanguage);
}
else
{
$moviedata['movies']=$this->main_model->getAllMovies();
}
$this->load->view('home/mainview.php',$moviedata);
}
Second : and if you want to add different view for different category of movies
You can do like this :
public function index()
{
$movielanguage=$this->input->get('language');
if(! empty($movielanguage))
{
$moviedata['popularmovies']=$this->main_model->getmoviebylanguage($movielanguage);
/*popularview is just an example*/
$this->load->view('home/popularview.php',$moviedata);
}
else
{
$moviedata['allmovies']=$this->main_model->getAllMovies();
/*allview is just an example*/
$this->load->view('home/allview.php',$moviedata);
}
}
Here is my controller:
class CommonController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('common_model'); //load your model my model is "common model"
}
public function add_work(){
$names = $_POST['name'];
$works = $_POST['work'];
$allValues = array(); // array to contains inserted rows
foreach($names as $key => $name){
$name= "your specified name";
$insertdata = array();
$insertdata['work'] = $works[$key];
$insertdata['name'] = $name;
$this->common_model->insert($insertdata);
array_push($allValues,$insertdata);
//$insert = mysql_query("INSERT INTO work(name,work) values ( '$name','$work')");
}
foreach($allValues as $insertRow){
echo $insertRow['work'];
echo $insertRow['name'];//this shows data well. but how to pass data in view.php
}
//view code will add here to show data in browser
}
Basically I want to pass all data to view.php for printing or exporting purpose. How can I do so.
To load a view you should do like this.
$this->load->view("filename");
If you want to pass data to view, you should do like this.
$this->load->view("filename",$data);
$data should have all parameters which you want to print in view.
The syntax goes like this.
$this->load->view("filename","data to view","Returning views as data(true / false");
If third parameter is true, view will come as data. It will not go to browser as output.
Edit:
Change
$this->load->view('print_view',$insertdata);
to
$data['insertdata'] = $insertdata;
$this->load->view('print_view',$data);
For more info, check this link
How CI Classes Pass Information and Control to Each Other
Calling Views
We will see.how the controller calls a view and passes data to it:
First it creates an array of data ($data) to pass to the view; then it loads and calls the view in the same expression:
$this->load->view('testview', $data);
You can call libraries, models, plug-ins, or helpers from within any controller, and models and libraries can also call each other as well as plug-ins and helpers.
However, you can't call one controller from another, or call a controller from a
model or library. There are only two ways that a model or a library can refer back to a controller:
Firstly, it can return data. If the controller assigns a value like this:
$foo = $this->mymodel->myfunction();
and the function is set to return a value, then that value will be passed to the variable $foo inside the controller.
//sample
public function display()
{
$data['text_to_display'] = $this->text_to_display;
$data['text_color'] = $this->text_color;
$this->load->view('display_view',$data);
}
Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view
loading method. Here is an example using an array:
$data = array(
’title’ => ’some’,
’heading’ => ’another some’,
’message’ => ’and another some’
);
$this->load->view(’view’, $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view(’view’, $data);
Sending Multiple Dimensional array
if we pull data from your database it will typically be
in the form of a multi-dimensional array.
<?php
class foo extends CI_Controller {
public function index()
{
$data[’Books’] = array(’POEAA’, ’TDD’, ’Clean C’);
$data[’title’] = "Title";
$data[’heading’] = "Heading";
$this->load->view(’view’, $data);
}
}
in view
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
<h3>My Books List</h3>
<ul>
<?php foreach ($Books as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
More Learning
NOTE:
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather
than sending it to your browser.The default behavior is false, which sends it to your browser. Remember to
assign it to a variable if you want the data returned:
$string = $this->load->view(’view’, ’’, TRUE);
Above will not solve your problem directly but definetly help in understanding concepts.
I know how AJAX call to CodeIgniter is working.
Edit for suggested answer
I tried redirection as a possible solution to my problem. I am not asking it as question. I am having problem passing parameter through URL and reusing view containing ajax post call. Also I am not aware how to post single value state_id which is already part of new_admission form.
I am loading city names for state_id of branch dynamically on $(document).ready()
When I call load_city() from admission() it works perfect.
XHR for load_city goes like:
localhost/project_folder/controller/load_city
But when I try edit_admission($studentId) it loads admission_view recursively inside <div id="city"></div>.
XHR for load_city goes like:
localhost/project_folder/controller/edit_admission/load_city
Here load_city is considered as parameter and edit_admission() is called recursively.
Controller:
public function load_city()
{
//load cities to $data from model
$this->load->view('city_view', $data);
}
public function admission()
{
//load init data for admission view from model
$this->load->view('admission_view', $data);
}
public function edit_admission($studentId)
{
//load init data for admission view from model
$this->load->view('admission_view', $data);
}
AJAX code:
function get_city() {
var parameters = {}; //instantiate the array
parameters['state_id'] = state_id;
$('#divcity').load('load_city', parameters, function (data) {
$('#city').combobox();
//code
});
};
load_city view:
<?php
echo '<select class="'.'form-control chzn-select col-lg-8 required'.'" id="'.'city'.'" name="'.'city'.'">';
echo '<option></option>';
foreach ($init_city['city_names'] as $row)
{
echo '<option value="'.$row->city_id.'">' .$row->city_name.'</option>';
}
echo '</select>';
?>
admission_view:
<div class="form-group">
<label class="control-label col-lg-4">City</label>
<div class="col-lg-8" id="divcity" name="divcity"></div>
</div>
I tried
public function edit_admission($studentId)
{
if(intval($studentId) > 0){
//load init data for admission view from model
$this->load->view('admission_view', $data);
} else if($studentId == 'load_city'){
//not passing post data to load_city()
redirect('branch/load_city');
}
}
Above code is not passing post data to load_city().
Also, I tried adding bellow code in routes.php
$route['edit_admission/load_city'] = 'load_city';
I did not get any success in both cases.
please help me, this is simple thing but I don't know why this still keep error for an hour,
on my view I've got :
<a href="admin/editProduct?idd=$id">
on my controller that directed from above :
public function editProduct(){
$data["id"] = $_GET['idd'];
$data["produk"] = $this->model_get->get_data_list(2);
//this below doesn't work either, i just want to past the parameter to my model
//$data["produk"] = $this->model_get->get_data_list($_GET['idd']);
$this->adminHeader();
$this->load->view("adminPages/editProduct", $data);
$this->adminFooter();
}
I can not use the array id. It keeps telling me undefined variable idd.
I don't know what to do anymore, please anyone help!
I am using Codeigniter framework
Change your view as:
<a href="admin/editProduct/<?php echo $id;?>">
And in the controller, either get the id as parameter,
public function editProduct($id) {
}
or as uri segment
public function editProduct() {
$id = $this->uri->segment(3);
}
Change your link (in view) with this
<a href="admin/editProduct/$id">
And change your controller as
public function editProduct($id) {
}
Then user $id inside your controller
Make the href link as follows:
...
And edit the controller like this:
public function editProduct($id){
...
$this->model_get->get_data_list($id);
}
Where $id will be the passed $id.
make
try this this works fine
public function editProduct()
{
$id=$this->uri->segment(3);
$data["produk"] = $this->model_get->get_data_list($id);
$this->adminHeader();
$this->load->view("adminPages/editProduct", $data);
$this->adminFooter();
}
I have a website where I am wanting to get some query results through AJAX and JSON, but I have absolutely no idea how to do it, I have this function,
public function category() {
$table = $this->uri->segment(2);
$content_id = $this->uri->segment(3);
$data['content'] = $this->site_model->get_content($table, $content_id);
$this->load->view('template/right-content', $data);
}
Essentially the query that is run is dynamic depending on what url is being passed, what I need to is, for the user clicks a link something like
Read the blog
From this link I get blog and 1 passed to the query, but I need to load the results in a view that is loaded in to my main template and then everytime a link is clicked do the same thing without overwriting the previous data, does anyone have any idea how to do this?
If I understand you correctly, you need to send an Ajax request to that url and then append it to the appropriate place in your document. Something like this:
$("#blog").click(function () {
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
success : function (html) {
$("#someDiv").append(html);
}
});
});
So that Codeigniter view should only contain the content, really, and perhaps some markup necessary to style it. The containers where the content goes should already be in the page where the link is originating.
Or, if you want actually want your data to come back as JSON you could do something like this
public function category() {
$table = $this->uri->segment(2);
$content_id = $this->uri->segment(3);
echo json_encode($this->site_model->get_content($table, $content_id));
}
AND, if you use the above authors method of using $.append, you'd want to modify your controller as such:
public function category() {
$table = $this->uri->segment(2);
$content_id = $this->uri->segment(3);
$data['content'] = $this->site_model->get_content($table, $content_id);
echo $this->load->view('template/right-content', $data, TRUE);
}