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.

+3


source to share


2 answers


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:

Get JSON POST data in CodeIgniter

+1


source


I solved this by doing ajax inside the button event (since I was passing arguments manually (var x = "some_argument") for testing) and it worked, I don't know exactly why it mattered, but it worked (if anyone knows why I'd like to know).



0


source







All Articles