Can't get data from JQuery Ajax request in Code Igniter
I am using AJAX to create a filtering engine, in my code I am fetching data from the filter fields and sending it to the controller via an AJAX request, when I get the data I update the table accordingly.
This is my Ajax Script:
var suppliername = "Apple";
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/Welcome/get",
dataType: "json",
data: {
supplier_name: suppliername,
},
success: function(html){
console.log("yay");
hot.loadData(html);
}
});
And this is my controller:
public function get(){
$where="";
$field="supplier_name";
$value=$this->input->post($field);
if($value!= null){
$supplier_name = $value;
$where = $where.$field.'="'.$value.'"';
$where = $where." AND ";
}
else{
$where = $where.$field.'='.$field;
$where = $where." AND ";
}
$field="category";
$value=$this->input->post($field);
if($value!= null){
$supplier_name = $value;
$where = $where.$field.'="'.$value.'"';
//$where = $where." AND ";
}
else{
$where = $where.$field.'='.$field;
//$where = $where." AND ";
}
echo json_encode($this->inventory_m->get(null,$where));
die();
}
when i manually change the values ββin the controller the filter works fine, but when i use $ this-> input-> post ($ field) it does nothing, i tried to print the get and post arrays and both are empty.
source to share
I am not allowed to comment, so I am posting it as an answer.
Here is my solution and explanation for the problem. This is because CodeIgniter cannot get JSON
. jQuery
does some under the hood tricks and converts your data to form-data-x
, so it works.
The solution is to use it $this->input->raw_input_stream
to extract yours JSON
and decode it with php
json_decode
. Check out the complete answer and the code below:
source to share