![]() |
How to get value from controller with jquery - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24) +--- Thread: How to get value from controller with jquery (/showthread.php?tid=68353) |
How to get value from controller with jquery - keziaendhy - 06-27-2017 Controller : function auto_barang(){ $id=$this->input->post('id'); $res= $this->barang_model->get_autocomplete($id); //foreach ($res as $rows){ // $hasil['stock']=$rows['stock']; //} //$this->output->set_content_type('application/json'); $this->output->set_output(json_encode($res)); } Script : <script> $(document).ready(function(){ $("#barang").change(function(){ $.post("<?php echo base_url()."index.php/pembelian/auto_barang"; ?>", { id:$("#barang option ![]() }, function(data){ alert(data); }); }); </script> Output : [{"id":"2","nama":"Lenovo ideapad 200","harga_beli":"2000000","harga_jual":"2500000","stock":"5"}] How to if I just want to take stock value? Thank you ! RE: How to get value from controller with jquery - InsiteFX - 06-27-2017 Try this: PHP Code: $this->output->set_content_type('application/json') RE: How to get value from controller with jquery - PaulD - 06-27-2017 Oh! I did not know that (set_content_type). Is that important? When I ajax with a json response in the controller I just json_encode the array and echo it. It has all worked fine up till now. Should I be setting the content type as well? Paul. PS the gaps in my knowledge continue to amaze me :-) RE: How to get value from controller with jquery - InsiteFX - 06-27-2017 The newer browser should know what type it is but I use it just to be safe. RE: How to get value from controller with jquery - rtenny - 06-28-2017 If you just need one field then just output that one field $this->output->set_output(json_encode($res['stock'])); RE: How to get value from controller with jquery - ciadvantage - 06-30-2017 I always do things like get result from query as array such as result_array() for multi dimension or single array like row_array() then simply For example , in your case, I would do this $res= $this->barang_model->get_autocomplete($id); //assume you get row_array as return then echo json_encode($res); OR I usually wrap it up with success and message, data like this: echo json_encode(array('success'=>1, 'message'=>'anything you want to read', 'data'=>$res)); My frontend at ajax, I often using Code: $.post(yoururl,{optionaldata},function(result){ |