javascriptjqueryjsonajax-request

Convert Json encoded data to javascript array and access value by index


I am getting json response from ajax like this

  echo  json_encode($data);

Ajax code:

  $.ajax({
        url:"PaymentSlip/check", 
        data:{val:val},
        type: 'POST',
        success:function(ajaxresult)
        {
            $("#jgoli").html(ajaxresult);
        }
    });

Result I am getting is:

     [{"paymentId":"2","paymentLabNo":"MR-622-040618",paymentTestId":"1"}]

Now I want to access my json array in javascript by index like

      ajaxresult[0] = 2; i.e paymentId=2
      ajaxresult[1] = 2; i.e paymentLabNo=MR-622-040618

How would I achieve that?

Note: I have tried many examples on stackoverflow, I know this question must have answered earlier. But I am still stuck. Any help would be appreciated.


Solution

  • $(document).ready(function(){
        var data =  [{"paymentId":"2","paymentLabNo":"MR-622-040618","paymentTestId":"1"}];
        //Loop on the object as key=>value
        $.each(data, function(key, value){
        //And diplay it in the result div
            $('#result').append('<p>'+data[key]['paymentId']+'</p>');
            $('#result').append('<p>'+data[key]['paymentLabNo']+'</p>');
             $('#result').append('<p>'+data[key]['paymentTestId']+'</p>');
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <div id="result"></div>