views:

606

answers:

4

Hi all,

I have an array of data that I'll echo to a page using PHP, and I want JQuery to be able to parse it. However, I don't want the data necessarily visible to the user. I have, for example:

<div id="data-1">
    <span id="width">5</span>
    <span id="height">10</span>
    <span id="depth">15</span>
</div>
<div id="data-2">
    <span id="width">10</span>
    <span id="height">20</span>
    <span id="depth">30</span>
</div>

I'm wondering if I should be storing data in spans this way, and then in JQuery, hiding them onload and play with the data by getting the span values later:

$(document).ready( function() {
    $("#width, #height, #depth").hide();
    $("#data-*").click(function() {
        var width = $("#width", $(this)).text();
        var height = $("#height", $(this)).text();
        var depth = $("#depth", $(this)).text();
    });
});

Is this the most efficient way to store data on the page? Should I be using instead, hidden inputs, or are there other ways to do this? Thanks!

A: 

I suspect you're going to get a lot of ajax based answers, but what your doing isn't really ajax. You're writing values out that are available when the server creates the page. Ajax would be the javascript calling back to the server to get that data.

So why not just use the php to write the script using the php?

$(document).ready( function () {
   $("#data-*").click(function() {
      var width = <?=$width_var_in_php?>;
      var height = <?=$height_var_in_php?>;
   });
});

My php is a bit rusty, but you should get the idea. Then there is nothing to hide, the javascript contains the data ready to go.

Tim Hoolihan
+4  A: 

When you are echoing your data with PHP, pass it through json_encode(), this will generate a javascript object that can be natively read by jQuery. You can then insert this at the bottom of the page when the request is made, or fetch it on-the-fly using AJAX.

PHP:

$my_data = array(
   'data1' => array(
      'width' => 16,
      'height' => 20
    ),
   'data2' => array(
      'width' => 16,
      'height' => 20
    )
);

# echo at bottom of page
echo '<script type="text/javascript">';
echo 'window.my_data = '.json_encode($my_data);
echo '</script>';

jQuery:

var height = window.my_data.data1.height
duckyflip
I like this idea! Thanks for the help -- and to everyone else, too.
Jasie
A: 

I have done this before with span's, but have been considering using the jQuery metadata plugin the next time I needed to do something similar.

Using your example, it could be structured like:

<div id="data-1" class="{width: 5, height: 10, depth: 15}"></div>
ern
A: 

Do you have to do it as HTML?

Could you simply output a JSON structure?

var data1 = {
                width: 5,
                height:10,
                depth:15
             }
...
Tom Hubbard