0

My Model-- iam getting data from Mysql database and returning it to controller

public function getCharges(){
    $where = "charge_type  = 'variable';
    $data = $this->read('charges',$where);
    return $data;
}

My Controller -- Here iam encoding the data in the json format to ajax

if (isset($_POST['method']) &&  $_POST['method'] == 'getCharges'){
     $this->load->model('Apiweb_m');
     $data = $this->Apiweb_m->getCharges();
     echo json_encode($data);
}

My AJAX

var method = "getCharges";
$.ajax({
    type: 'POST',
    data: 'method='+method,
    url : api_url+"apiweb",
   /* dataType: "json",*/
    success:function(msg){
        var data =  $.parseJSON(msg);
        console.log(data);// here iam getting Parse error 
    },
    error:function(Xhr, status, error){
        console.log(Xhr);
        console.log(status);
        console.log(error);
    }
Harish
  • 29
  • 7
  • Please add sample ajax response which you are getting, Additionally if it response is correct then `contentType: 'application/json'` add in request – Smit Shah Apr 27 '17 at 11:35

2 Answers2

0

change function in model to :

public function getCharges(){
    $where = "charge_type  = 'variable'";
    $data = $this->read('charges',$where);
    return $data;
}

and ajax:

var method = "getCharges";
$.ajax({
    type: 'POST',
    data: {method:method},
    url : api_url+"apiweb",
    dataType: "json",
    success:function(msg){
        var data =  $.parseJSON(msg);
        console.log(data);// here iam getting Parse error 
    },
    error:function(Xhr, status, error){
        console.log(Xhr);
        console.log(status);
        console.log(error);
    }
Abanoub Makram
  • 463
  • 2
  • 13
0

You have to set dataType ajax property json.Hope you will do it like that.

var method = "getCharges";
$.ajax({
    type: 'POST',
    data: 'method='+method,
    url : api_url+"apiweb",
    dataType: "json",
    success:function(msg){
        var data =  $.parseJSON(msg);
        console.log(data);// here iam getting Parse error 
    },
    error:function(Xhr, status, error){
        console.log(Xhr);
        console.log(status);
        console.log(error);
    }
Waqas Ahmed
  • 185
  • 2
  • 11