php - Ajax Json data - How to access the returned Json data -
when click on listproduct
(which invoice no) open collapsible table listing products matching invoice no.
my view file:
<script> $(document).ready(function(){ $(".listproduct").click(function(){ var value = $(this).text(); alert(value); $.post('<?=site_url("purchase_controller/getproductlist"); ?>', {data:value},function (result) { alert(result[1][1]["invoiceno"]); for(i=1;i<result["count"];i++){ //loop trough elements $('#products tr:last').after('<tr><td>' + result[i]['invoiceno'] + '</td><td>' + result[i]['productname'] + '</td><td>' + result[i]['price'] + '</td></tr>'); } }); $(".collapse").collapse('toggle'); }); }); </script> <table id="products"> <tbody> <tr> <td >invoice no</td> <td>productname</td> <td> quantity</td> <td> price</td> <td> amount</td> </tr> </tbody> </table>
my controller file:
public function getproductlist(){ // check if ajax request // if($this->input->is_ajax_request()){ // echo "entered"; // checks if variable data exists on posted data if($this->input->post('data')){ //query in model should verify if data passed legit before querying $query = $this->purchasemodel->getproductlists($this->input->post('data')); $data['records'] = $query['records']; $data['count'] = $query['count']; $this->output->set_content_type('application/json'); $this->output->set_output(json_encode($data)); return $data; } // } }
my output when debugged - response ajax:
{ "records": [ {"id":"39","invoiceno":"55","price":"30000","quantity":"2", "amount":"60000","productname":"tab"}, {"id":"41","invoiceno":"55", "price":"200","quantity":"4","amount":"800","prod uctname":"zdsfs"} ], "count":2 }
but error getting:
typeerror: result[1] undefined alert(result[1][1]["invoiceno"]);
jquery's parsejson()
function parse json string.
var resultobj = $.parsejson( result ); alert(resultobj.records[1].invoiceno);
reference: http://api.jquery.com/jquery.parsejson/
Comments
Post a Comment