It’s easy to add PHP data to a page as JavaScript data using json_encode, but sometimes you to relate that data to a specific element. For example, while rendering a series of objects in a for loop, you might want to way to associate an object ID with each of their containing <divs> for use by the JavaScript on the page.
One way to do this is by using PHP to generate a JavaScript variable mapping object ID to a set of data about the object, and then including the ID in the markup in some way, such as <div class="id-123">.... This works, but it complicates the implementation and is just not elegant.
The solution I found was to include a small snippet of JS at the top of every page that allowed me to add PHP data to the markup in such a way that it would be associated with specific elements. It looks like this:
<div class=”address”>
<div class=”jsdata” title=”address-id”><?php echo $id;?></div>
<span>123 Lollipop Lane, Mushroom Kingdom 84297</span>
</div>
In this case it’s just a numeric value, but it could just as easily contain a JSON-encoded object using json_encode. Supporting this is incredibly simple and gracefully degrades if support isn’t there. First, this needs to be included in the stylesheet:
.jsdata {display:none;}
This way nobody sees this data ever. Next, you include the JavaScript to do the work. My implementation is below, using jQuery, but it could be implemented without it without must more effort.
jQuery(function($) {
$(‘.jsdata’).each(function() {
var node = $(this).parent(),
raw = $(this).text(),
parsed = $.parseJSON(raw),
title = $(this).attr(‘title’) || ‘jsdata’;node.data(title, parsed);
$(this).remove();
});
});
