How to get value from controller with jquery |
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 !
Try this:
PHP Code: $this->output->set_content_type('application/json') What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
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 :-)
The newer browser should know what type it is but I use it just to be safe.
What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
If you just need one field then just output that one field
$this->output->set_output(json_encode($res['stock']));
On the package it said needs Windows 7 or better. So I installed Linux.
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){ |
Welcome Guest, Not a member yet? Register Sign In |