1

I've got an array in PHP which I'm passing to my view for use within the JavaScript.

So what I've got is:

stdClass Object
(
    [tones] => Array
    (
        [0] => Array
        (
            [id] => 114
            [sleep_session_id] => 55
            [responded_to] => 
            [in_bed] => 1
            [created] => 1316443267104
            [inserted] => 2011-09-19 14:43:04
        )
    )
)

$(function () {
    var tones = $.parseJSON(<?php echo json_encode($this->tones); ?>);
    alert(tones);
});

Which results in something along the lines of:

<script type="text/javascript">
    $(function () {
        var tones = $.parseJSON([{"id":114,"sleep_session_id":55}]);
        alert(tones);
    });
</script>

All I'm getting back is null, the jQuery is definately loaded and I've checked the JSON in jsonlint.com and it appears valid

Hope you can help me out

Andy

3 Answers 3

6

If your server-side data are in JSON, there's no need to use $.parseJSON in Javascript.

$(function () {
    var tones = <?php echo json_encode($this->tones); ?>;
    alert(tones);
});
Sign up to request clarification or add additional context in comments.

Comments

4
$(function () {
        var tones = $.parseJSON('[{"id":114,"sleep_session_id":55}]');
        alert(tones);
    });

1 Comment

jesus, i must be half asleep still :D thanks guys. So silly when something like this knacks you off enough to post on StackOverflow only to realise that you've asked a really really stupid question :) thanks again all. I ended up just echoing out php json_encode on it. Seemed neater and i dont trust js :D
2

parseJSON parses a JSON string, so enclose your encoded array in quotes :

$(function () {
    var tones = $.parseJSON('<?php echo json_encode($this->tones); ?>');
    alert(tones);
});

See this example

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.