Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JSON data from php to html-data attribute and then to Javascript

i'm creating a plugin in which the user adds custom settings in data- attribute in HTML. Settings are in JSON format. I'm using these settings in Javascript.

It has got preview, base and paths properties. preview and base have string values, but paths is an array of path objects.

It works fine when i add JSON setting directly into the HTML:

<div data-side="front" data-params='{"preview": "assets/img/products/tshirt/front-preview.png", "base": "assets/img/products/tshirt/front-base.png", "paths": "[{\"name\": \"base\", \"path\": \"M 324.00,33.00 C 324.00,33.00\", \"x\": 92, \"y\": 16, \"height\": 370}, {\"name\": \"collar\", \"path\": \"M 358.00,46.10 C 358.00,46.10\", \"x\": 170, \"y\": 17, \"height\": 21}, {\"name\": \"leftSleeve\", \"path\": \"M 633.17,170.00 C 633.17,170.00\", \"x\": 288, \"y\": 66, \"height\": 131}, {\"name\": \"leftCuff\", \"path\": \"M 595.00,438.00 C 615.47,438.23\", \"x\": 293, \"y\": 172, \"height\": 33}, {\"name\": \"rightSleeve\", \"path\": \"M 142.00,140.00 C 143.46,150.28\", \"x\": 47, \"y\": 64, \"height\": 131}, {\"name\": \"rightCuff\", \"path\": \"M 48.00,375.38 C 48.00,375.38 95.00\", \"x\": 41, \"y\": 166, \"height\": 36}]"}'> 

I'm getting this value using data('Params') method of jQuery. Its type is object.

Now, when i'm trying to json_encode a php array and pass it to the data-, it's added successfully

<div data-side="front" data-params=<?php echo "'".json_encode($dataParams)."'"; ?>> 

But now typeof data('Params') in Javascript is string. So, i'm getting a JSON parse error. If i remove paths key, its type changes to object.

Here's the print_r of the array that i'm encoding:

Array (     [preview] => assets/img/products/tshirt/front-preview.png     [base] => assets/img/products/tshirt/front-base.png     [paths] => Array         (             [0] => Array                 (                     [name] => base                     [path] => M 324.00,33.00 C 324.00,33.00                     [x] => 92                     [y] => 16                     [height] => 370                 )                 ... and more path arrays          )  ) 

So, why does it changes its type to string if i include paths key? Any way to solve it?

Edit:

Here's the output:

Output

like image 644
Kanav Avatar asked Sep 28 '15 10:09

Kanav


1 Answers

You need to escape data and handle special characters.

<div data-side="front" data-params="<?php echo htmlspecialchars(json_encode($dataParams), ENT_QUOTES, 'UTF-8'); ?>"> 

And get it with jQuery:

$('[data-side="front"]').data('params'); // object 

or javascript

JSON.parse(document.querySelector('[data-side="front"]').dataset.params); // object 
like image 50
Rene Korss Avatar answered Oct 05 '22 12:10

Rene Korss