0

In another question, it was pointed out that using semantic markup can be a really clean way to pass data to an onclick function, along the lines of the code below.

I have a second question relating to passing JSON and having the receiving function recognize it as such. I have a PHP generated JSON value of [{"authed":"2012-03-04 17:24:24"},{"authed":"2012-03-04 11:44:38"}] that I need to pass to a function. echoing that straight into the <a> tag won't work, so I am using urlencode() to get:

<a href="javascript:void(0)" data-auth="%5B%7B%22authed%22%3A%222012-03-04+17%3A24%3A24%22%7D%2C%7B%22authed%22%3A%222012-03-04+11%3A44%3A38%22%7D%5D" onclick="popup(this)">click</a>

Unfortunately, when I alert this out from popup(), I via the following code:

function popup(t) {
  var auth = t.getAttribute('data-auth');

  alert(decodeURI(auth));
}

I get

[{"authed"%3A"2012-03-04+17%3A24%3A24"}%2C{"authed"%3A"2012-03-04+11%3A44%3A38%22"}]

which JSON.parse() is unable to handle. Any suggestions on decoding/passing JSON using this pattern?

4
  • so I am using urlencode() to get: --- why so? You don't use it in a url Commented Mar 5, 2012 at 4:30
  • @zerkms if I don't, all that I get in popup is "[{", everything else is cut off as the first occurrence of a double quote seems to be interpreted as the end of the data-auth attribute. Commented Mar 5, 2012 at 4:34
  • You need to use htmlspecialchars() to escape for html--like you should be doing for everything you echo out in html. Don't use urlencode(), which is for encoding parts of a url path or query parameter. Commented Mar 5, 2012 at 4:38
  • @FrancisAvila That did it, you've got the anser if you post that below, thanks. Commented Mar 5, 2012 at 4:40

1 Answer 1

0

You need to use htmlspecialchars() to escape for html--like you should be doing for everything you echo out in html. (You are doing that right? To prevent generating invalid html?) Don't use urlencode(), which is for encoding parts of a url path or query parameter.

<?php
$data = array(array('authed'=>'2012-03-04 17:24:24'), array('authed'=>'2012-03-04 11:44:38'));
$jsondata = json_encode($data);
?>
<a data-auth="<?php echo htmlspecialchars($jsondata, ENT_COMPAT, 'UTF-8')?>" onclick="popup(this)">click</a>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.