1

I've got this element which activates a modal and is supposed to pass information to a javascript function to do some actions on the newly opened modal.

Here is my HTML

<i
style="cursor:pointer;"
uk-toggle="target: #edit_product"
data-uid="{{ @product[uid] }}"
data-data="{{ json_encode(@product) }}"
class="material-icons edit_product">edit</i>

Notice data-data contains a json encoded array, that array looks like this:

Array (
    [uid] => 1
    [name] => dasd
    [supplies] => Array
        (
            [0] => Array
                (
                    [supplyid] => 4
                    [amount_per] => 5
                    [cost] => 0.0013024691358025
                )

            [1] => Array
                (
                    [supplyid] => 1
                    [amount_per] => 10
                    [cost] => 0.05798
                )

        )

    [total_cost] => 0.059282469135802
    [total_consumables] => 15
)

This element has the class edit_product, which I have a click handler on:

$(".edit_product").click("click", function() {
    var data = JSON.parse($(this).data('data'));
    console.log(data);
});

But the quotes in the json encoded string are not allowing the javascript to grab this information, I always get the error:

Uncaught SyntaxError: Unexpected token o in JSON at position 1

How can I pass this data to my javascript?

What I've tried:

I tried changing data-data="{{ json_encode(@product) }}" to data-data='{{ json_encode(@product) }}' so that the quotes should not need to be escaped, but my HTML is still rendering with the double quotes for some reason, and I get the same error.

I've tried wrapping json_encode() with addslashes() but I got an error similar to the above one except the token is a slash.

I tried changing my javascript to pull the data from php by using PHP opening and closing tags inside the javascript, but I couldn't figure out how to select the actual array row that I need, where the data-data method would send only the subarray that I need instead of the full array.

GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71

0 Answers0