Welcome Guest, Not a member yet? Register   Sign In
Using JSON in data attributes with JS
#2

(This post was last modified: 11-14-2017, 05:36 PM by ivantcholakov. Edit Reason: typos )

For views I use the Twig parser and here is a test on how I would do this:

Code:
<div id="test_element" data-json="{{ '{ "value_1": "A test string value.", "value_2": 2 }'|e('html_attr') }}"></div>

<script>

    $(function() {

        var data_json = $('#test_element').attr('data-json');
        alert(data_json);

        var data = JSON.parse(data_json);
        alert(data.value_1);
        alert(data.value_2);
    });

</script>

This works, and the produced HTML code looks like this:

Code:
<div id="test_element" data-json="&#x7B;&#x20;&quot;value_1&quot;&#x3A;&#x20;&quot;A&#x20;test&#x20;string&#x20;value.&quot;,&#x20;&quot;value_2&quot;&#x3A;&#x20;2&#x20;&#x7D;"></div>

<script>

    $(function() {

        var data_json = $('#test_element').attr('data-json');
        alert(data_json);

        var data = JSON.parse(data_json);
        alert(data.value_1);
        alert(data.value_2);
    });

</script>

For PHP views this example would be:

Code:
<div id="test_element" data-json="<?php echo html_attr_escape('{ "value_1": "A test string value.", "value_2": 2 }'); ?>"></div>

<script>

    $(function() {

        var data_json = $('#test_element').attr('data-json');
        alert(data_json);

        var data = JSON.parse(data_json);
        alert(data.value_1);
        alert(data.value_2);
    });

</script>

The helper function html_attr_escape() is introduced by me, it calls the Twig's escaper to do the job.
https://github.com/ivantcholakov/starter...n.php#L283

If you don't need Twig to be installed in your project, you can implement html_attr_escape() by using the escaper form Zend. https://github.com/zendframework/zend-es...r.php#L155 The escapers of Twig seem to be ported from Zend. I can see that CodeIgniter 4 would use the Zend Escaper, you can back-port this function: https://github.com/bcit-ci/CodeIgniter4/...n.php#L219 :

Code:
<div id="test_element" data-json="<?php echo esc('{ "value_1": "A test string value.", "value_2": 2 }', 'attr'); ?>"></div>

In conclusion, you should find a way to escape the data html attribute as html attribute, it does not matter whether it would contain json data or something else. I think, the trivial way would be the best here, everyone would understand it without getting bored or tired.
Reply


Messages In This Thread
RE: Using JSON in data attributes with JS - by ivantcholakov - 11-14-2017, 05:34 PM



Theme © iAndrew 2016 - Forum software by © MyBB