Undefined Object Property JS

Matthew B
Matthew B used Ask the Experts™
on
I am trying to access the properties of this object but i keep getting undefined. This is what i return from PHP json_encode($return, true);

i try to access results.message (undefined)
or results.status (undefined)

My jquery:

jQuery.ajax({

url: "order_sync.php",
method: 'post',
dataType: 'json',
data: {
  order: obj
},
error: function(){
    
},
success: function(results){


  if(results.status === '0'){


    $(order_button).closest('.error').show();

  } else {

$(order_button).closest('.success').show();

  }

}

})

Open in new window



This is the JS returned to me from PHP and an ajax call:

[  
   {  
      "status":"1",
      "message":"Some Message.",
      "order_id":"6336",
      "country":"United States",
      "customer_name":"Customer",
      "ship_method":"Fedex Ground (Fedex Ground)"
   }
]

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Looking at your JS, your object is contained within an array, so you'd need to access the first element of the array before accessing the object - results[0]:

if(results[0].status === '0'){

It probably makes more sense to edit your PHP to make sure you just return just the object rather than the array containing the object.
Matthew BHack

Author

Commented:
Thank you Chris.

I resolved this by creating an object in my PHP and return this instead of returning an array.

           $object = new stdClass();
            $object->status = '1';
            $object->message = 'message';
            $object->order_id = $orderId;
            $object->country = $orderCountry
            $object->customer_name = $orderDetails;
            $object->ship_method = $orderShippingDetails ;

$object_json = json_encode($object,true)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial