0
<ul id="listmhs">
    <li class="daftar">Budi</li>
    <li class="daftar">Indah Setia</li>
    <li class="daftar">Tono</li> 
</ul>
<script>
   var listmhs = document.getElementById('listmhs')
   var daftar = document.querySelectorAll('.daftar')
   listmhs.addEventListener('click', function(el) {
      if (el.target.classList.contains('daftar')) {
           if (el.target.firstElementChild === null) {
               var tagul = document.createElement("ul")
               var tagli1 = document.createElement("li")
               var name = el.target.textContent
               var isitext1 = '<?php
                               $myPhpVar = 'Here I need to use name js variable';
                               $sql = "SELECT * FROM mahasiswa WHERE nama = $myPhpVar";
                               $stmt = $pdo->query($sql);
                               foreach ($stmt as $row) {
                                   echo $row["nama"];
                               }
                               ?>'
              var text1 = document.createTextNode(isitext1)
              tagli1.appendChild(text1)
              tagul.appendChild(tagli1)
              el.target.appendChild(tagul)
        }else {
              el.target.firstElementChild.classList.toggle('hidden')
         }
    }
})
</script>

I need to get data from database by php but I need a value of tag html variable which be got use js. I used cookie but it isn't working well because browser must be reload to update data.

  • You can't, JS is after PHP. Use AJAX and send the data to PHP after. Also your PDO usage is insecure use `prepare` and parameterize your query. – user3783243 Jan 30 '21 at 14:36
  • Does this answer your question? [using JS variable in PHP](https://stackoverflow.com/questions/8226915/using-js-variable-in-php) – Nebril Jan 30 '21 at 16:55

0 Answers0