skip to Main Content

I try to take object from my controller, when I console.log(response) it show the value correctly which is in

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

unfortunately I try to use the object like response.itemValue when I console it show undefined. I try var object = response. during the console it show the same value. Please I want to use the 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 controller where I encode the object into Json

$row = $getProcess->fetch();


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

3

Answers


  1. Chosen as BEST ANSWER

    It worked, by changing this few item

    $object[] = array(); 
    

    into

    $object = array();
    
    

    and JSON.parse(data)

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

  2. Your response is an array. So you need to access it like

    response[0].itemValue
    

    or you can loop through the array

    response.forEach(element => {
      console.log(element.itemValue);
    });
    

    Below is the example

    const response = JSON.parse(`[
        {
        "itemValue":100,
        "itemUnit":"2"
        }
    ]
    `);
    
    response.forEach(element => {
      console.log(element.itemValue);
    });
     
    
    Login or Signup to reply.
  3. I recommend using the jQuery library. For parsing JSON, simply do

    var obj = JSON.parse(data);
    // Accessing individual value from JS object
    alert(obj.itemValue); 
    alert(obj.itemUnit);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search