2

From my API I get a json object with data. The special data is converted to HTML entities (using htmlspecialchars). Looks like this:

    {
        id: "0",
        title: "Hello & good day",
    }

However, when i fetch the data using $.getJSON, and insert the data into the input value, the & is still there.

How can I avoid this?

FooBar
  • 5,752
  • 10
  • 44
  • 93

2 Answers2

2

You can create a dummy element to pass the HTML entity in as the dummy element's html, then pass the text() of that dummy element to the input element's value:

var $dummy = $('<div/>', { html: 'Hello &amp; good day'});
$('input').val($dummy.text());

JSFiddle demo.

In one line:

$('input').val($('<div/>', { html: 'Hello &amp; good day'}).text());
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • I like. Would there be a way to do this with the whole response? The response from json: `$.getJSON(.., function(response) {` As there will be multiple fields which needs to be escaped. – FooBar Mar 19 '14 at 10:59
1

If you are able to change the PHP to encode the text using rawurlencode, you can decode the string before setting it as the input value using:

input.value = decodeURIComponent(jsonData.title);

(assuming that jsonData.title is the encoded string from the response.

steveukx
  • 4,370
  • 19
  • 27
  • Well, I can change the PHP code. But, thinking an extra time, should i just use htmlspecialchars_decode on the output then? Before the javascript recieves the data? Is it even needed to convert to entities on json results? Hm. – FooBar Mar 19 '14 at 11:02
  • If you're sending the content with `json_encode` in your PHP, that will already be escaping quotes for you - so you may not need to. – steveukx Mar 19 '14 at 11:10