0

How can I use a PHP variable inside the Javascript onclick=function?

<?php
  for($i=0;$i<10;$i++){
    echo '<li><div><a  href="#" onclick="showPopUp("' . $mobile_image_link[$i+$p] .'","' .$mobile_image_link[$i+$p] .'");"><img src='. $mobile_image_link[$i+$p] .' width="160" height="165" alt="" border="0" /></a></div></div></li>';
  }
?>

4 Answers 4

1

Just concatenate the strings, and use backslashes to escape the necessary quotes:

echo '
 <a href="#"
    onclick="showPopUp(\''. $mobile_image_link[$i+$p].'\',
                       \''. $mobile_image_link[$i+$p].'\');">
     <img src="'.$mobile_image_link[$i+$p].'" alt="" />
 </a>'

Would result in:

<a href="#"
    onclick="showPopUp('http://mylink.com/1',
                       'http://mylink.com/2');">
     <img src="http://mylink.com/image.png" alt="" />
 </a>

On a side note, please read the HTML latest specifications, setting tag style using width="", height="" and border="" is deprecated and discouraged

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

Comments

0

Simply echo php variable in javascript code:

<script type="text/javascript">
       var js_variable= <?php echo $php_variable; ?>
</script>

Comments

0

Either use the double quotes approach (php variables are only inserted into double quote strings.

<?php for($i=0;$i<10;$i++){
  echo "<li><div><a href=\"#\" onclick=\"showPopUp('$mobile_image_link[$i+$p];','$mobile_image_link[$i+$p];');\"><img src=\"$mobile_image_link[$i+$p]\" width="160" height="165" alt="" border="0" /></a></div></div></li>";}
?>

or do what you already did for the img tag. You'll need to escape some quotes to make it work.

<?php for($i=0;$i<10;$i++){
  echo '<li><div><a href="#" onclick="showPopUp(\''.$mobile_image_link[$i+$p].'\',\''.$mobile_image_link[$i+$p].'\');"><img src="'.$mobile_image_link[$i+$p].'" width="160" height="165" alt="" border="0" /></a></div></div></li>';}
?>

Comments

0
<?php 
  for($i=0;$i<10;$i++){
     $onclickvariable = "showPopUp('".$mobile_image_link[$i+$p]."','".$mobile_image_link[$i+$p]."');"
echo '<li><div><a  href="#" onclick="'.$onclickvariable.'">
     <img src='.$mobile_image_link[$i+$p].' width="160" height="165" alt="" border="0" /></a>
</div></li>';}
?>

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.