0

Good evening, I'm trying to send an encoded JSON via the onclick attribute.

Unfortunately this JSON contains articulated strings with many apostrophes and quotes. As you can well understand the JSON closes the quotes of the onclick attribute.

Edit 1

This is in a "return" of jquery DataTables loaded by ajax and the json is obviously different for item so i can't make an addEventListener (correct me if I'm wrong).

i need this getJsonObj() function to open a modal with all information inside

{data: null,
        render: function (data, type) {
          const json = JSON.stringify(data);
          console.log(json);
          return `<a onclick="event.preventDefault();getJsonObj(${json})"style='cursor: pointer' id='modalApp' class='orange-link uk-text-bold uk-text-uppercase'>${data.full_name}</a>`;
        },
}

This is the output:

Example

Any ideas to be able to send it without problems?

Edit 2

Im not using any framework, only javascript, jquery, and Jquery datatables

C7 Lab
  • 15
  • 4

1 Answers1

1

You are putting a string into HTML so it needs to be HTML escaped. Specifically, in your case, the quotes from the JSON string are closing the quotes from the HTML onclick attribute. Use the function below and the quotes in your JSON will be replaced with &quot;

function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

<a onclick="event.preventDefault();getJsonObj(${escapeHtml(json)})"style='cursor: pointer' id='modalApp' class='orange-link uk-text-bold uk-text-uppercase'>${data.full_name}</a>

See Can I escape html special chars in javascript?

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • And for unescape how can i do it? – C7 Lab Oct 14 '20 at 07:33
  • You don't have to unescape it, just like you don't need to unescape characters you've escaped in a JS string such as `Hello\tWorld`. The JS engine will parse it and it will know that it means "Hello[tab]World", and the HTML parsing engine will know that ` – Ruan Mendes Oct 14 '20 at 12:13
  • Thanks, very helpful – C7 Lab Oct 14 '20 at 14:42