Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON object properties are undefined

I'm getting a JSON object back from an AJAX call and logging the result like this:

console.log(response);

And this is the response logged in the console:

{"filename":"new.jpg","orientation":"vertical"}

However, when I

console.log(response.orientation);

I get a response that it is undefined.

Most of the answers I've read indicate that an array was returned instead of an object and that response[0].orientation should work, but that is not the case here. When I assign the same array to another variable in the console:

var obj = {"filename":"new.jpg","orientation":"vertical"}

Then obj.orientation returns the correct value.

I'm creating the JSON object in PHP:

$response=array('filename' => $newfilename, 'orientation' => $orientation);
$response=json_encode($response);
echo $response;

Is it apparent why the properties are showing undefined?

like image 605
Bryan Gentry Avatar asked Mar 16 '26 00:03

Bryan Gentry


2 Answers

Either put:

header("Content-type: application/jason");

in the PHP, specify dataType: "json" in the AJAX call in the JavaScript, or call JSON.parse.

like image 175
Barmar Avatar answered Mar 18 '26 14:03

Barmar


You will need to parse your string to get a proper JSON object. JSON.parse(response); will provide you with a JSON object from which you can read the properties

like image 44
Romain Avatar answered Mar 18 '26 13:03

Romain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!