Zaxter
Zaxter

Reputation: 3035

Cant read php JSON encoded data in js

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

Upvotes: 0

Views: 80

Answers (2)

Jeremy Thille
Jeremy Thille

Reputation: 26360

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' :)

Upvotes: 2

NaijaProgrammer
NaijaProgrammer

Reputation: 2957

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.

Upvotes: 2

Related Questions