2

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?

2
  • if your response is a string you'll have to pass it through JSON.parse before you can access properties. also, there's no such thing as a JSON object Commented Aug 31, 2012 at 12:52
  • can you post your code about how your sending ajax request and success function Commented Aug 31, 2012 at 12:52

4 Answers 4

6

Either put:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

JSON.parse (or $.parseJSON in jQuery) did the trick. I don't know why it wasn't in the several tutorials I read... Thank you!
Seems to be a common problem, hardly a day goes by that we don't see someone ask essentially the same question.
2

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

Comments

1

Can you try the following example in jsfiddle.

This is not the better way you can use JSON.parse(); or $.parseJSON(); (jquery version)

But if this is your problem, json being returned as a string this fix it and you can alter your code

http://jsfiddle.net/dadviegas/gf8Yq/

Comments

0

I think the ajax / php part should look like Ajax

$.ajax({
        type: "POST",   
        url: "link.php",
        dataType: "json",
        success: function(result){
             alert(result.orientation); 
        }
    });

PHP

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

Make sure that use at least 5.2 php version

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.