0

I need to pass a localized multidimensional javascript object to a page. The object is constructed using php and represents some wp-theme settings. I cant find a way to utilize wp_localize_script for this, as it will not parse multidimensional arrays.

Instead I've come up with the solution to use a html5 data-* attribute for this and then using jQuery to retrieve it, hoping for this method to provide x-browser compatibility.

So on the page where I need to access the localized data I let php output:

<div id="localized" style="display:none" data-localized='{"user": "Doe", "skills": {"html":5, "css":4, "php":3} }'>

I then get that localized data using:

var my_localazed_data = $('#localized').data('localized');

It works fine. But my concern here is:

1) Is this browser compatible?

2) Are there any security concern to be aware of as compared to using wp_localize_script?

1 Answer 1

1

Q: 1.) Is this browser compatible?

Yes, for all browsers supporting jQuery data(). jQuery is generally supported by most modern browsers.

Q: 2) Are there any security concern to be aware of as compared to using wp_localize_script?

wp_localize_script() is mainly doing the same but it's keeping the data on the serverside and not within the DOM.

As always, making use of javascript and interacting with the DOM has security implications. You need to follow the rules to properly en- and de-code any arbitrary data safely so that injections can not introduce unintended behaviour.

2
  • 1
    what do you mean its keeping the data server side? The data is rendered to the html source code in both cases. wp_localize_script will result in the data being printed out as a JS object inside a script tag, whereas the other method results in the data being printed out as a JSON formatted attribute value for some dom element. But even if the first method does not attach the data to a dom element, it still does not keep it server side? Feb 6, 2011 at 20:14
  • 1
    wp_localize_script: data on server, output as javascript. // yours: data on server, output as HTML, that HTML read from javascript then. It's pretty the same only slight differences.
    – hakre
    Feb 6, 2011 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.