Reputation: 335
I'm attempting to echo the following line of HTML through PHP
echo "<a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass('$id', '$formattedDate', '$time')'></a><p class='text-center'>".$formattedDate." @ $time</p>";
I don't get an error. But the quotes for onClick='cancelClass... don't get parsed properly, which leads to the javascript function not executing.
How it gets color coded in Google Chrome Source View
How it should get color coded (example of another function)
Upvotes: 0
Views: 635
Reputation: 5868
Using double quotes in HTML. Using htmlspecialchars with ENT_QUOTES to escape values which have double quote.
echo '<a class="fa fa-ban fa-2x cancelClass" onClick="'.htmlspecialchars("cancelClass('$id', '$formattedDate', '$time')", ENT_QUOTES).
'"></a><p class="text-center">'.$formattedDate." @ $time</p>";
Upvotes: 0
Reputation: 61984
They do get parsed properly, however you specified the wrong ones to use. Javascript can't differentiate between the quotes to wrap your string variables and the quotes to wrap the "onclick" value, it thinks the onclick ends too early.
To differentiate them you'll have to escape them then. using \"
for the ones inside the brackets.
echo "<a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass(\"$id\", \"$formattedDate\", \"$time\")'></a><p class='text-center'>".$formattedDate." @ $time</p>";
should do the trick.
Alternatively, don't use echo for the whole string, simply output most of it direct:
?> //temporarily stop interpreting the file as PHP, so the next bit will be output directly as raw HTML
<a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass("<?php echo $id;?>", "<?php echo $formattedDate; ?>", "<?php echo $time;?>")'></a><p class='text-center'>".$formattedDate." @ $time</p>
<?php //continue with PHP
Upvotes: 1
Reputation: 306
You need to do something like:
echo "<a class='fa fa-ban fa-2x cancelClass' onClick=\"cancelClass('".$id."', '".$formattedDate."', '".$time."')\"></a><p class='text-center'>".$formattedDate." @ $time</p>";
Upvotes: 1
Reputation: 644
Change it to the following
echo "<a class=\"fa fa-ban fa-2x cancelClass\" onClick=\"cancelClass('$id', '$formattedDate', '$time')\"></a><p class=\"text-center\">".$formattedDate." @ $time</p>";
escaping the attribute double quotes you can have a normalized html
Upvotes: 2