I am serializing a form that contains one select input with an object as its value to be sent to the back-end via Ajax:
<select name="language" class="form-control">
<option value="" selected disabled>Choose a Language</option>
<option value="{ locale: 'AF', name: 'Afrikaans' }">Afrikaans</option>
...
</select>
The data is then sent via Ajax, using VueJS:
$.post("/ajax/admin/languages", $("#addLanguageForm").serialize()).done((data) => {
if (data.success) {
toastr.success("A new language has been added");
} else {
toastr.error("An error occurred");
}
})
Then, the method called by the route is triggered, and here I am checking the data by logging it:
public function store(Request $r)
{
$x = $r->input('language');
Log::info($x);
}
Will display the following:
[2018-01-29 05:52:18] local.INFO: { locale: 'AF', name: 'Afrikaans' }
I then tried to access these keys to store their values by $x->locale and $x->name, which causes the error, even being an object.
What could I be missing?
With some help and ideas, I come up with a solution. First, I modified the JSON format as #JigarShah suggested, and then, from within the Controller, following code:
public function store(Request $r)
{
$x = $r->input('language');
$d = json_decode($x);
print_r($d->name);
}
All ok.
Related
I am learning CodeIgniter; in my program I am trying to populate a dropdown from mysql database but I seemed to be doing something wrong.
Please find below what I tried:
Model
In my model I tried to use different select methods I found online but all failed so I stick with the below method and still failed.
function getAllVendors()
{
$this->db->select('DISTINCT SUBSTRING(product_code,1,3) as vendor')
->order_by('vendor');
$q = $this->db->get('tec_sale_items');
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Controller
public function allVendors(){
$this->data['vendors'] = $this->vendors_sales_model->getAllVendors();
$this->page_construct('reports/vendors_sales_details', $this->data);
}
View
<select class="form-control">
<option value="">All</option>
<?php
foreach($vendors as $ven)
{
echo '<option value="'.$ven['vendor'].'">'.$ven['vendor'].'</option>';
}
?>
</select>
Could someone please point me to what I am doing wrong.
As I see you might be forget to call view into your controller. Load view in the controller $this->load->view("your view file name") and pass the data you got from your database.
First make sure that you are getting proper data from model. And as I see your are using current object of class $this->data['vendors'] so you have to use same in the code
<select class="form-control">
<option value="">All</option> <?php
foreach($this->data['vendors'] as $ven)
{
echo '<option value="'.$ven['vendor'].'">'.$ven['vendor'].'</option>';
}
?>
</select>
May be it's helpful 🙂.
And you should use ci4 it's 3rd version of ci and it's no longer maintained. For better security and performance change php server 7.4 and above.
So I try to create a page for category with dropdown, but I can't direct it to the function for each category that I've chosen and load the form view.
This is the view for choosing the category first
<select name="jenisberkas" id="jenisberkas" onchange="this.form.submit()">
<option value="roya">Roya</option>
<option value="peralihan">Peralihan</option>
<option value="validasi">Validasi</option>
</select>
<button type="submit">Submit</button>
And this is my controller look like,
function __construct()
{
parent::__construct();
$this->load->helper('url')
}
public function get_jenisberkas()
{
if(isset($_POST) && !empty($_POST())
{
if($jenisberkas = $this->input->post('jenisberkas')=='roya'; {
$data['jenisberkas'] = $jenisberkas;
$this->load->view('roya_v',$data); //directing to the form view for this category
}
elseif ($jenisberkas = $this->input->post('jenisberkas')=='peralihan';
{
$data['jenisberkas'] = $jenisberkas;
$this->load->view('peralihan_v',$data); //directing to the form view for this category
{
What I want is when an option is clicked and submitted, it will go directly to specific page form that I made for each options, while passing the value to the page.
I know there's something wrong with my controller and I think I don't need a model since this form doesn't involve a database.
Following is the code fixed:
public function get_jenisberkas()
{
if(isset($_POST) && !empty($_POST)) // Removed () from here, added )
{
if($this->input->post('jenisberkas') == 'roya') {
$data['jenisberkas'] = $jenisberkas; // Fix it yourself
$this->load->view('roya_v',$data);
}
elseif ($this->input->post('jenisberkas')=='peralihan')
{
$data['jenisberkas'] = $jenisberkas; // Fix it yourself
$this->load->view('peralihan_v',$data);)
{
I would recommend to use an Intelligent Code Editor like
https://www.eclipse.org/kepler/
UPDATE:
Well, after more than an hour thinking about it, i solved it myself (lmao) with a simple code in my form category view. And after i clicked the submit button, it will go to the specific function made for each category (yay!), that's what i actually want.
so i'm gonna put it here just incase some people out there maybe need solution for this silly case.
this is the view
if (isset($_GET["jenisberkas"])) {
redirect('mulaiberkas/' . $_GET["jenisberkas"] . "");
exit();
}
?>
<form method="get" action="">
<select name="jenisberkas" id="jenisberkas" onchange="this.form.submit()">
<option value="roya">Roya</option>
<option value="peralihan">Peralihan</option>
</select>
<button type="submit">Submit</button>
</form>
and the controller is simply contains function named as the value chosen
function __construct()
{
parent::__construct();
$this->load->helper('url');
}
function roya()
{
$jenisberkas = $this->input->get('jenisberkas');
$data['jenisberkas'] = $jenisberkas;
$this->load->view('roya_v', $data);
}
function peralihan()
{
$jenisberkas = $this->input->get('jenisberkas');
$data['jenisberkas'] = $jenisberkas;
$this->load->view('peralihan_v', $data);
}
}
I'm having difficulty with display data from the db to dropdown.
This is what I have tried:
form_model.php
function getEmployee()
{
$this->db->select('username');
$query = $this->db->get('tbl_usrs');
return $query->result();
}
form_controller.php
public function evaluate()
{
$data['employee'] = $this->form_model->getEmployee();
$this->load->view('evaluate_view');
}
evaluate_view.php
<select class="form-control">
<?php
foreach($employee as $row)
{
echo '<option value="'.$row->username.'">'.$row->username.'</option>';
}
?>
</select>
It's giving me an error saying I have an unidentified variable employee in my view file. I've seen problems relating to this but so far all their solutions didn't work for me.
When you load the view you have to send the data like this:
$this->load->view('evaluate_view', $data);
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.
I Need help on how can i get values of second select box based on first select box
This is view:
$(document).ready(function() {
$('#state').change(function() {
// Get an instance of the select, and it's value.
var state = $(this),
stateID = state.val();
// Add if statement to check if the new state id
// is different to the last to prevent loading the same
// data again.
// Do the Ajax request.
$.ajax({
url : 'http://localhost/ci_ajax/select/get_cities/'+stateID, // Where to.
dataType : 'json', // Return type.
success : function(data) { // Success :)
// Ensure we have data first.
if(data && data.Cities) {
// Remove all existing options first.
state.find('option').remove();
// Loop through each city in the returned array.
for(var i = 0; i <= data.Cities.length; i++) {
// Add the city option.
state.append($('option').attr({
value : data.Cities[i].value
}).text(data.Cities[i].city));
}
}
},
error : function() {
// Do something when an error happens?
}
});
});
});
<form action="" method="post">
<select name="state" id="state">
<option>Select</option>
<?php foreach($states as $row):?>
<option value="<?php echo $row->id?>"><?php echo $row->states;?></option>
<?php endforeach;?>
</select>
<select id="cities" name="cities">
<option>Select</option>
</select>
This is controller:
class Select extends CI_Controller{
function index(){
$data['states']=$this->load_state();
$this->load->view('form',$data);
}
function load_state(){
$this->load->model('data_model');
$data['states']=$this->data_model->getall_states();
return $data['states'];
}
function get_cities() {
// Load your model.
$this->load->model('data_model');
// Get the data.
$cities = $this->data_model->get_cities();
// Specify that we're returning JSON.
header('content-type: application/json');
// Return a JSON string with the cities in.
return json_encode(array('Cities' => $cities));
}
}
This is model:
class Data_model extends CI_Model{
function getall_states(){
$query=$this->db->get('states');
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
function get_cities(){
$this->db->select('id,cities');
$this->db->from('cities');
$this->db->where('s_id',$this->uri->segment(3));
$query=$this->db->get();
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
}
Please help on this hopefully provide the correct code.
Because you are accessing the get_cities() function directly, rather than from another function in the controller, your return statement will not actually print the json array to the page.
return json_encode(array('Cities' => $cities));
There are 3 ways to print it: the first is to print or echo the json array (bad practice), the second is to use a view that prints the raw text sent to it. I.E.
$this->load->view('raw', array('data' => json_encode(array('Cities' => $cities)));
With raw.php being just:
<?php print $data; ?>
Or finally you can use the set_output() function in the output class like this:
$this->output->set_output(array('data' => json_encode(array('Cities' => $cities)));
You may also want to make your function load_state() private if it is only going to be accessed from the index() function.
You may have other problems with your code but that is the most obvious one.