Search code examples
phpjavascriptdata-transfer

Is there a javascript equivalent of php's urldecode or html_entity_decode()?


I've got an associative array in php that I want to stick into a hidden form input so that I can later get the values in javascript. Because of quoting issues, I need to urlencode the json, or htmlentity it. Once I have the object in javascript, though, what's the easiest way to get it back to plain ol' json?

OR is there a better way to approach this issue? AJAX seems like overkill here -- I'd rather pre-populate the data on the page, rather than setting up multiple requests. I suppose I could write the php object to the page inside a php-generated script tag, but that seems a bit messy, and I'm not certain that [scripts] will be parsed in every possible situation where this might be used.


Solution

  • If you stick the data within a field you could use decodeURIComponent to decode the value. Example:

    decodeURIComponent("%5b'hello'%2c%20'world'%5d"); // ['hello', 'world']
    

    Another approach might be to embed the JSON object in a <script> element in the PHP output. You could even go as far as to make the JSON object an argument to a function that stores it away somewhere.

    <script>setupData(<?= toJSON(['hello', 'world']) ?>)</script>
    

    When the page loads the setupData would be called with the literal ['hello', 'world'].