How to transfer data from controller to jquery (Ajax) in codeigniter

controller code

$rates['poor'] = 10; 
$rates['fair'] = 20;

$this->load->view('search_result2', $rates);

//I have tried this in many ways but at least It executes the "success" in ajax file only with above way.  other ways I have tried ex :-
//$this->output->set_output(json_encode($rates));
//echo json_encode($rates);

I need to pass this array of bets to ajax

js code

$.ajax({
    type:'POST',
    url:'some url',
    data:{'adID':adID},
    //dataType:'JSON', // when I uncommented this it displays nothing. when commented it displays "undefined" on the label below i have created
    success:function(rates){ 

        $('#rate_val').html('<label>'+rates.poor+'</label>');

        //I have tried this in many ways  ex :-
        // $('#rate_val').html('<label>'+rates['poor']+'</label>');
        // $('#rate_val').html('<label>'+rates[0]+'</label>');

    }
});

"undefined" is displayed. I can not get the data that I transferred from the controller. please, help?

+1
source share
2 answers
  • Uncomment dataType:'JSON'
  • Set output as json using echoor set_outputfrom a controller
  • Get item using rates.pooror rates['poor']from ajax

controller

public function post_url()
{
    $rates = array();
    $rates['poor'] = 10; 
    $rates['fair'] = 20;

    $this->output->set_output(json_encode($rates));
}

Ajax

<script>
$.ajax({
    type:'POST',
    url:'POST_URL',
    data:{'adID':adID},
    dataType:'JSON',
    success:function(rates){ 
        $('#rate_val').html('<label>'+rates.poor+'</label>');
    }
});
</script>
0
source
$data['a']='100';
$data['b']='200';
echo json_encode(array('success'=>$data));

JQuery

<script>
$.ajax({
    type:'POST',
    url:'POST_URL',
    data:{'adID':adID},
    dataType:'JSON',
    success:function(rates){
       var data     = jQuery.parseJSON('['+response+']');

        $('#rate_val').html('<label>'+data.succcess.a+'</label><label>'+data.succcess.b+'</label>');
    }
});
</script>

I believe that it can be executed the way you want.

0
source

Source: https://habr.com/ru/post/1657566/


All Articles