Home  >  Q&A  >  body text

How to get value from Encode json data on php page

I try to get the object from the controller and when I console.log(response) it displays the values ​​in it correctly

[
    {
    "itemValue":100,
    "itemUnit":"2"
    }
]

Unfortunately, when my console says undefined, I try to use an object like response.itemValue. I try var object = response. During console it shows the same value. I want to use response data.

if(itemID){
            $.ajax({
                type:'POST',
                url:'?syspath=ajax&controller=ajax&action=getActItemDose',
                data: { 'itemId': itemID, 'itemType': itemType },
                
                
                success:function(response){
                    
                    // var obj = jQuery.parseJSON(data);
                    console.log(response);
                    
                   
                    var object = response;
                    var value = object.itemValue;
                    var unit = object.itemUnit;
                    console.log(object);
                    console.log(value);
                }
            }); 
        }

This is my controller encoding the object to Json

$row = $getProcess->fetch();


                $object[] = array(
                    'itemValue' => $row['each_dose'],
                    'itemUnit' => $row['unit_dose']
                );
                    echo json_encode($object);

P粉715228019P粉715228019410 days ago548

reply all(2)I'll reply

  • P粉106301763

    P粉1063017632023-09-07 13:47:50

    By changing these few items, it worked

    $object[] = array();

    Enter

    $object = array();

    and JSON.parse(data)

    var object = JSON.parse(data);
    value = object.itemValue;
    unit = object.itemUnit;

    reply
    0
  • P粉354602955

    P粉3546029552023-09-07 11:29:06

    I recommend using the jQuery library. To parse JSON, just do

    var obj = JSON.parse(data);
    // Accessing individual value from JS object
    alert(obj.itemValue); 
    alert(obj.itemUnit);

    reply
    0
  • Cancelreply