awmayhall
awmayhall

Reputation: 45

Php echo javascript with variables

have a question about a php echoing script that has a link to a javascript with some variables. I need to know the format for the echo so it will work properly. Could anyone shed any light on this? My code is posted below

echo "<a href='javascript: toggle('variable1', 'variable2')'><label1 for='nameEditor'>Manage</label1></a>";

Now when you hover over the link it just shows javascript:toggle( Now I have tried multiple things and I still cant get it to work. Anyone have any suggestions?

Upvotes: 2

Views: 7473

Answers (3)

Jared Farrish
Jared Farrish

Reputation: 49188

It's because you're mixing your quotes that the browser see. Do this:

echo "<a href=\"javascript: toggle('variable1', 'variable2')\"><label1 for='nameEditor'>Manage</label1></a>";

If you escape the double quotes (\"), you'll be fine. The browser itself is seeing '''' (all single quotes), so you need to retain "''" (double,single,single,double) in your html element attribute, irregardless of PHP (except for the escaping).

Upvotes: 0

Marc B
Marc B

Reputation: 360592

Assuming variable1 and variable2 are the PHP bits you want inserted into the javascript, then

echo "<a href='javascript: toggle('$variable1', '$variable2')'><label1 for='nameEditor'>Manage</label1></a>";

However, be aware that if either of those variables contain Javascript metacharacters, such as a single quote, you'll be breaking the script with a syntax error (think of it as the same situation as SQL injection).

To be sure that the variable's contents become legal Javascript, you'd want to do something like:

<script type="text/javascript">
    var variable1 = <?php echo json_encode($variable1); ?>;
    var variable2 = <?php echo json_encode($variable2); ?>
</script>

<a href="javascript:toggle(variable1, variable2)...">...</a>

Upvotes: 4

FeRtoll
FeRtoll

Reputation: 1267

try like this:

echo "<a href=\"javascript: toggle('variable1', 'variable2')\"><label1 for='nameEditor'>Manage</label1></a>";

you have to escape \ quotes

Upvotes: 0

Related Questions