Skip to content Skip to sidebar Skip to footer

Pass Javascript To Php In Modal Window

I am trying to pass a javascript variable to php in a modal window, all on the same page, which is edit.php. (I'll figure out how to do it with separate pages later). In the meanwh

Solution 1:

PHP is executed before your page is loaded.

You can do this via Ajax, when JS is triggered, by calling your PHP script and passing the id as a param:

<script type="application/javascript">
 $(document).on("click", ".open-EditRow", function () {
   var myGroupId = $(this).data('id');
   $(".modal-body #groupId").val( myGroupId );

   // ajax callvar url = "/path/to/script.php?id=" + myGroupId;
   $.get(url, function(data){
     // do something with the result         
   });
 });
<script>

You could also open the modal once you get the response and if there is an error don't open it and show an error message instead. But it depends on your use case.

UPDATE

Your PHP script looks basically like your code, except you get the id as param from the request. Try something like this:

<?php$id = $_GET['id']

   $sql = "SELECT mygroup FROM mytable WHERE `pk_tId`='$id'";
   $result = mysql_query($sql);
   if($result) {
     if(mysql_num_rows($result) == 1) {
       $row = mysql_fetch_assoc($result);
       echo$row;
     }
     else {
       echo"Cannot seek row: " . mysql_error() . "\n";
     }
   }
   else {
     echo"Cannot seek row: " . mysql_error() . "\n";
   }
?>

Solution 2:

I eventually added an onclick function to the modal a href and created a cookie which I grabbed once the modal was opened. I used javascript to clear the cookie when I closed the modal.

Post a Comment for "Pass Javascript To Php In Modal Window"