0

I'm calling a php script via AJAX which returns a json encoded object.

$.post("php/getCamera.php", {
        cam_id: identifier
        }, function(data){
            console.log(data);
            //var camera = JSON.parse(data);
            var camera = $.parseJSON(data);
            console.log(camera.name);
            console.log(data['name']);
            console.log(camera['name']);
    });
}

Here's my php script:

<?php
    require 'Camera.php';

    $camera = new Camera();
    if(isset($_POST["cam_id"])) {
        $cam_obj = $camera->getCamera($_POST['cam_id']);
        $cam_obj_array = get_object_vars($cam_obj);
        echo json_encode($cam_obj_array);

    }
?>

And here's my camera class:

class Camera
{
    public $id;
    public $name;
    ...

}

In the js console, I see the encoded data, but I can't access its elements:

{"id":"6","name":"camera 1"}
undefined
undefined
undefined
undefined

2 Answers 2

2

add 'json' at the end of your post request :

$.post("php/getCamera.php", {
        cam_id: identifier
        }, function(data){
            console.log(data);
            console.log(camera.name);
            console.log(data['name']);
            console.log(camera['name']);
    }, 'json');
}

It's a shorthand for full ajax syntax dataType: "json".

Better, use getJSON instead of post (but then, remove 'json' :)

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

Comments

2

Try this:

console.log(data.name);

It appears, from your log, that the data is already a JSON object, and so needs no further parsing.

1 Comment

It's not JSON. It's treated as a string, because the dataType has not been specified.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.