1

It's just an example, but with this code, it works. But if I change 5 to "5" and 10 to "10" I got an Unexpectid ending syntax error for the echo line

PHP

$array = array();
$array[0] = 10;  
$array[1] = 5; 
$json = json_encode($array);

echo "<td style=\"background: red;\"><button onclick=\"modifyModalContent('$day_date_column','$i',$json) ... (really long line)

JS

function modifyModalContent(date, id, array) {
  var header = document.querySelector(".modal-header");
  var body = document.querySelector(".modal-body");

  var table =
  `
  <table class="table table-bordered table-hover">
    <tr>    
      <td>${array[0]}<td>
      <td>${array[1]}<td>
    </tr>
  </table>
  `;

  body.innerHTML = table;

  header.innerHTML = `<h1> Date: ${date}</h1></br><h1>ID: ${autoid}</h1>`;
}

The two echo line after run:

That works:

<tr style="height: 137px;"><td style="background: red;"><button onclick="modifyModalContent('2019-01-21','1',[10,5])" ... (long line) 

And if I use it with a string array got error on this:

<tr style="height: 137px;"><td style="background: red;"><button onclick="modifyModalContent(2019-01-21,1,["10","5"])" ... (long line) 

How could I do the same with an array like this:

$array = array();
$array[0] = "10";  
$array[1] = "5"; 

I guess the problem is because of the " char, but How could I fix it?

4
  • 1
    Look at the output of the problem line, you have unescaped quotes in quotes, you need to escape them Commented Jul 15, 2019 at 12:38
  • I see it, but what can I do with it? Can I replace it? Commented Jul 15, 2019 at 12:38
  • You can do $json = str_replace('"', "'", json_encode($array)); Commented Jul 15, 2019 at 12:44
  • Possible duplicate of How to properly escape quotes inside html attributes? Commented Jul 15, 2019 at 12:49

2 Answers 2

3

I'd recommend using the PHP function htmlspecialchars -- that will not only take care of issues with quotes, but any other characters (&, <, >} that should be turned into HTML entities before being used as HTML attribute values.

$json = htmlspecialchars(json_encode($array));

Sign up to request clarification or add additional context in comments.

Comments

1

Replace ["10","5"] with ['10','5']

More information about simple and double quotes: When to use double or single quotes in JavaScript?

2 Comments

The array is in a variable, I call it like modifyModalContent('$day_date_column','$i',$json). Can I change the " to ' in that $json array ?
Yes you can do it with PHP

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.