0

Im using a well known "hack" (the json encode function) to prevent some characters to mess up my html, im receiving from an API a description field that can content single or double quotes (and other special chars). So:

<div class="someThing" data-fulldescription=<?=json_encode($textFromApi);?>>
  ...
</div>

Now I read that data field using jquery and then print it inside a div:

$('#brand-modal-content').html($(this).parents('.someThing').data('fulldescription'));

The problem is, the quotes are now coded by the PHP function, and some characters get replaced by "\u00e8" or "\u00f9", is there a way to reformat the text using jquery?

1 Answer 1

2

You are injecting content into HTML in a very wrong (and even unsafe) way. Do this instead:

data-fulldescription="<?=htmlspecialchars(json_encode($textFromApi));?>"

This way the JSON will be properly encoded and safely injected no matter what is inside; then, you can decode it like so:

var decoded = JSON.parse($(this).parents('.someThing').data('fulldescription'));

The combination of these steps will perfectly preserve the JSON no matter what it represents (you can take shortcuts if you assume it's a string, but why not be always 100% safe?). You can then do whatever you want with the decoded value.

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.