1

I am trying to insert html code through a php variable in javascript. I am getting the following error below. Please can someone advise?

Error Message: "Unexpected Identifier 'Inactive'" ($option has values 'Inactive'/ 'Active')

PHP

$tr_active_Options = '';
$sql1 = "SELECT status FROM tr_active";
$result = $mysqli -> query($sql1);
while($row = $result -> fetch_assoc()){
$option = $row['status'];

$option = '<div class="dpOtions" onclick="track.addChosenOption(\''.$option.'\', \'act_ui\')">'.$option.'</div>';

$tr_active_Options .= $option;
}


$tr_active = '<div class="drpClass"><div class="dropOptionsDiv" id="actList_ui">'.$tr_active_Options.'</div></div>';

JAVASCRIPT

document.getElementById('anchor').innerHTML = '<div id="editWrap"><?php echo $tr_active; ?></div>';

1 Answer 1

1

The ' in your string are terminating the JavaScript string you've started with '.

You can safely have PHP generate a string for use in JavaScript using json_encode, like so:

document.getElementById('anchor').innerHTML =
    '<div id="editWrap">' +
    <?php echo json_encode($tr_active); ?> +
    '</div>';

Note how the JavaScript string ends, then we use + to join it with the one that PHP will output (json_encode will handle the strings), then we + it with another JavaScript string after it. What the browser will see will look like this:

document.getElementById('anchor').innerHTML =
    '<div id="editWrap">' +
    "contents of $tr_active here" +
    '</div>';

...which is valid.

That said: Using PHP to generate HTML with embedded JavaScript inside attributes is asking for a world of hurt. Separate those concerns! :-)

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.