Home > Back-end >  Is it acceptable to use htmlentities() before passing data to JavaScript?
Is it acceptable to use htmlentities() before passing data to JavaScript?

Time:07-05

I'm retrieving some data from a database (all using prepared statements) into an array, then outputting that data as JSON

I then process the data with JavaScript and display it on the web page (as a list).

Is it acceptable to run htmlentities($data, ENT_QUOTES) on the DB results as I'm adding them to the array before converting it to JSON and outputting it? Will I run into any issues doing so?

Or should I do all of this using JavaScript? Usually, I would always use htmlentities() before outputting data directly onto a web page, but I'm not sure if it's OK to do so when I'm using JSON and parsing the data with JavaScript. As far as I'm aware there's no similar function in JS either.

The database has text fields and could contain anything (including things which will break a web page)

Edit: Example code (PHP side)

$DB_results = array('Test', '123', '<b>hello</b>', 'B&$B%');

echo json_encode($DB_results);

JS code:

var db_results = JSON.parse(this.responseText); // this is from an AJAX query

var dbr_length = db_results.length;

for (var i = 0; var i < dbr_length; i  )
{
    var li = document.createElement('li');
    li.appendChild(document.createTextNode(years[i]));
    document.getElementById('mylist').appendChild(li);   
}

Should I amend the PHP code to the following (keep in mind htmlentities() would be added while adding the data to the array

$DB_results = array(
    htmlentities('Test', ENT_QUOTES),
    htmlentities('123', ENT_QUOTES),
    htmlentities('<b>hello</b>', ENT_QUOTES),
    htmlentities('B&$B%', ENT_QUOTES)
);

echo json_encode($DB_results);

CodePudding user response:

I think you've answered the question yourself, but if you want more confidence, you can reference the MDN docs for Document.createTextNode():

Creates a new Text node. This method can be used to escape HTML characters.

And the code in your question (slightly modified in order to execute without ReferenceErrors):

document.body.appendChild(document.createElement('ul')).id = 'mylist';

const json = `["Test","123","<b>hello</b>","B&$B%"]`;
const dbResults = JSON.parse(json);

for (const str of dbResults) {
  const li = document.createElement('li');
  li.appendChild(document.createTextNode(str));
  document.getElementById('mylist').appendChild(li);
}

  • Related