Sending javascript variable by post method from view to controller of Codeigniter but when i access it in controller post array showing empty.
type: "POST", method:"POST", both are not working
My view
<input type="month" id="reg_month" name="reg_month" onchange="sort_by_reg_month()" class="form-control" placeholder="Month of Reg Users" autofocus="autofocus">
my javascript code
//sort student by month of registration
function sort_by_reg_month(){
var reg_month = $('#reg_month').val();
if(reg_month)
{
$.ajax({
url:"<?php echo base_url().'Users/get_user_sort_by_reg_month'; ?>",
method:"POST",
data:{
"reg_month":reg_month
},
success:function(data)
{
alert('Student sorted by reg_month.');
},
error: function() {
alert('Something is wrong...');
}
});
}
location.reload();
}
//controller Users
//sort student by geristration month
public function get_user_sort_by_reg_month(){
$reg_month = $this->input->post('reg_month');
var_dump($reg_month);
if ($reg_month) {
$time=strtotime($reg_month);
$month=date("F",$time);
$year=date("Y",$time);
$result['users'] = $this->Users_model->sort_by_reg_month($month,$year);
}else{
$result['users'] = $this->Users_model->get_user();
}
Want to access post data but showing an empty array
The problem is here:
url:"<?php echo base_url().'Users/get_user_sort_by_reg_month'; ?>"
Maximum that you could append to this line is index.php
, but, if you've removed it via config
and .htaccess
, then you need to append nothing. It means next:
url:"Users/get_user_sort_by_reg_month"
or
url:"index.php/Users/get_user_sort_by_reg_month"
Check this out, it works for me. If you'll need my working example, I'll present it to you here.
My example:
HTML:
<input type="month"
id="reg_month"
name="reg_month"
onchange="sort_by_reg_month();"
class="form-control"
placeholder="Month of Reg Users"
autofocus="autofocus"
/>
JS:
$(function() {
//sort student by month of registration
});
function sort_by_reg_month(){
var reg_month = $('#reg_month').val();
if(reg_month)
{
$.ajax({
url:"index.php/page_work/get_user_sort_by_reg_month",
method:"POST",
data:{
"reg_month":reg_month
},
success:function(data)
{
// var_dump from php
// alert(data);
alert('Student sorted by reg_month.');
},
error: function() {
alert('Something is wrong...');
}
});
}
// I don't need it (because it reloads page and I'll not see the result)
// location.reload();
}
Controller:
public function get_user_sort_by_reg_month(){
$reg_month = $this->input->post('reg_month');
return var_dump($reg_month);
/*
if ($reg_month) {
$time=strtotime($reg_month);
$month=date("F",$time);
$year=date("Y",$time);
$result['users'] = $this->Users_model->sort_by_reg_month($month,$year);
}else{
$result['users'] = $this->Users_model->get_user();
}*/
}