Search code examples
javascriptphphtmlonclickhref

How to pass php variables in a link with onclick?


I have this while statement that generates dynamic links.

<?php while($panelchat=mysqli_fetch_array($panechatresult)){?>
  <a href="?chatwithuser=<?=$panelchat['fromUserId'];?>&username=<?=$panelchat['ProfileName'];?>" onclick="document.getElementById('window').style.display='block';">
 <?=$panelchat['ProfileName'];?>
 </a>
<?php}?>

Onclick it displays a div called window

<div id="window" style="display:none;"></div>

I need to pass variables from href to display in <div id='window'> So far it works but since the page refreshes, the <div id='window'> does not stay and goes back to initial status which is display:none.

How can I make this happen without refreshing the page so that I can display variables inside the <div id='window'>?


Solution

  • You are confused about backend and frontend routines. You can pass php variables to the onclick, but your routine it's too simple, you don't need all of that. When the user clicks on the link, just get sure some of that data is loaded and delete window's display none style. Like that:

    <?php while($panelchat=mysqli_fetch_array($panechatresult)){?>
      <a href="?chatwithuser=<?=$panelchat['fromUserId'];?>&username=<?=$panelchat['ProfileName'];?>" onclick="document.getElementById('window').style.display='block';">
     <?=$panelchat['ProfileName'];?>
     </a>
    <?php}?>
    $windowStyle = (isset($_GET['chatwithuser']) && isset($_GET['username'])) ? 'display: none;' : '';
    echo "<div id='window' style='{$windowStyle}'></div>";