Vlad
Vlad

Reputation: 1797

JS inside PHP Escape String (for functions)

I have a PHP script that generates some Javascript for me in a manner like this:

foreach ($array as $element)
{
    echo '<a onClick="myFunctionTakesPHPValues('.$element[0].','.$element[1].')">'.$element[2].'</a>';
}

My problem is that how can I escape so that the Javascript bit will look more like

<a onClick='MyFunctionTakesPHPValues("'.$element[0].','.$element[1].'")>'.$element[2].'</a>';

I hope this makes sense. The short version is that I feel i need triple quotes inside double quotes inside single quotes, but there is no such thing as triple quotes, but I believe there is some way to escape quotes to nest it up three times.

Upvotes: 1

Views: 346

Answers (5)

Your Common Sense
Your Common Sense

Reputation: 157828

  1. Never echo JS from PHP. Escape from PHP mode instead, it will save you a lot of slashes and nerves.
  2. Every value have to be escaped properly, as explained in this article

So, for the JS values you have to escape them with json_encode() and, as they are going into HTML attribute, escape them as HTML too.
For the last element only HTML encoding is required.

foreach ($array as $element) 
{
    $param1 = htmlspecialchars(json_encode($element[0])); // better give them 
    $param2 = htmlspecialchars(json_encode($element[1])); // meaningful names
    $param3 = htmlspecialchars($element[2]);
?>
<a onClick="myFunctionTakesPHPValues(<?=$param1?>,<?=$param2?>)">
   <?=$param3?>
</a>
<? }

And yes, using raw JS in HTML attributes considered as a bad practice.

Upvotes: 2

twitch
twitch

Reputation: 225

foreach ($array as $element)
{?>
<a onClick="myFunctionTakesPHPValues("<?php echo $element[0].','.$element[1].')>'.$element[2].'</a>'
} 
?>

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

Same as always: encode as JSON.

echo '<a onClick="myFunctionTakesPHPValues('.json_encode($element[0]).','.json_encode($element[1]).')">'.$element[2].'</a>';

Upvotes: 3

Gimmy
Gimmy

Reputation: 3911

Use this:

echo "<a onClick='MyFunctionTakesPHPValues(\"'".$element[0]."','".$element[1]."'\")>'".$element[2]."'</a>'";

Upvotes: 1

Swapnil
Swapnil

Reputation: 616

Use Like

echo "<a onClick='myFunctionTakesPHPValues(\"".$element[0]."\",\"".$element[1]."\")'>".$element[2]."</a>";

Upvotes: 1

Related Questions