0

I am printing some php data into a field on my page. The data is json_encoded by the backend.

Now i want to retrieve this information and turn it into a javascript object...

$(document).ready(function(){
    $('.trigger-info-change').click(function(){
        var rel = $(this).attr('rel');
        var td_id = 'info-'+rel;
        var data = $('#'+td_id).html();

        console.log(data);
    });
});

now data is correctly console logging my "object" like this:
{"data":{"id":"1","data1":"1","data2":"2"},{"id":"2","data1":"3","data2":"4"}}

Now the question is how do i turn this html into a actual javascript object... I've tried to use jQuery.parseHtml, and some other things google advised but no luck... would i need a script or is there something like that out there?

Thanks in advance!

1

2 Answers 2

3

If you want use Jquery:

var json = $.parseJSON(data)

Or

var obj = JSON.parse(data);
Sign up to request clarification or add additional context in comments.

Comments

0

I think this better to print out JSON String in javascipt.

<script>
    var data = <?php echo $json ?>;
</script>

Which makes :

<script>
    var data = {"data":{"id":"1","data1":"1","data2":"2"},{"id":"2","data1":"3","data2":"4"}};
</script>

But if you insist on your way, use JSON.parse(jsonString).

2 Comments

lol thanks for the reply, but i don't have the specific data object available to me, it is assigned and then read... so there is no "new" backend call to refresh the object in this way
I answered because you said "The data is json_encoded by the backend.". However ... ;) :D

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.