0

I am iterating over an array to display some data, and at the same time creating another array which will be used to create JSON and then assign it to a JavaScript variable.

<?php
$otherStuff=array();
foreach($myArray AS $row)
{
    echo("<tr data-id='{$row['id']}'><td>{$row['firstname']}</td><td>{$row['firstname']}</td></tr>");
    $otherStuff[$row['id']]=$row['otherStuff'];                
}
echo('<script type="text/javascript">var otherStuff='.json_encode($otherStuff).';</script>');
?>

This just doesn't seem like a very clean way to do this task. Instead I am wondering if it would be better to create some hidden HTML, and then clientside parse it to create the desired JavaScript variable.

Is doing so possible? Is it a good idea, or should I do something else? If possible, how?

Thank you

user1032531
  • 24,767
  • 68
  • 217
  • 387
  • Personally, I like the way you're doing it currently and I wouldn't change it. It's the way that requires the least effort and is relatively clean and understandable. – GravityScore Oct 12 '14 at 15:33
  • If the `otherStuff` is related the HTML row's data, why not use `data-` attributes to store it in relation with the `tr` element? – Jared Farrish Oct 12 '14 at 15:35
  • @JaredFarrish I like the idea, but is it possible being an array? – user1032531 Oct 12 '14 at 15:37
  • @user1032531: Sure. One row = one array entry. – T.J. Crowder Oct 12 '14 at 15:39
  • Yes, of course. `data-other-stuff='{"stuff":"goes heres"}'` That can be turned into an array the same as what you have. Note, though, that you need to encode it in PHP so the double-quotes aren't a problem. – Jared Farrish Oct 12 '14 at 15:39
  • @JaredFarrish My data is just integers, so I encoding is really easy. So, just create JSON in the data element, and when accessed, it will automatically turn into an object? Will this work?: `data-other-stuff='["stuff":"goes heres","more stuff":"more goes heres"]'` – user1032531 Oct 12 '14 at 15:44
  • @T.J.Crowder Please elaborate. Are you saying the same as Jared? – user1032531 Oct 12 '14 at 15:45
  • @user1032531: Sorry, yes, I was answering your question to Jared. Your `id`-based approach is also absolutely fine, but the great thing about putting the data *on* the element is that it's nice and direct. You'd do it like this: `echo("...");` – T.J. Crowder Oct 12 '14 at 15:46
  • @T.J.Crowder My `id` approach works, but I would rather not have script located throughout the HTML and I feel it is harder to troubleshoot. Agree? – user1032531 Oct 12 '14 at 15:48

1 Answers1

1

Here is a rudimentary example:

$arr = array('stuff' => 'goes here');

echo "<div data-other-stuff='" . htmlspecialchars(json_encode($arr)) . "'></div>";

Produces:

<div data-other-stuff='{&quot;stuff&quot;:&quot;goes here&quot;}'></div>

http://codepad.org/Bq5GZcVS

$('div').each(function ea(){
    // Some browsers/versions do not support JSON.parse(), try json2.js
    var data = $(this).attr('data-other-stuff'),
        _data = JSON.parse(data);

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

Produces (in the console):

'{"stuff":"goes here"}' Object {stuff: "goes here"} 

(The first is really a string, but I added the single quotes to make that obvious.)

http://jsfiddle.net/0mv44jvd/1

Just like any JSON-encoded, you have to turn it into an array or object once you consume it. But this works all the same.

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • So, `eval` is needed? The data is safe, so it isn't a problem. Just paranoid from all those people saying "eval is evil! Never use is!" – user1032531 Oct 12 '14 at 15:52
  • See [this answer](http://stackoverflow.com/a/4935684/451969), I just didn't want to bother with `JSON.parse()`. I use the library recommended, though, which [uses `eval()` as a shim](https://github.com/douglascrockford/JSON-js/blob/master/json2.js#L474). – Jared Farrish Oct 12 '14 at 15:55
  • Seems like parsing is automatic in jQuery's `data()` method. See http://jsfiddle.net/0mv44jvd/2/ – user1032531 Oct 12 '14 at 16:40