0

I have a button inside a loop. When the user clicks on the button I want to create a $_SESSION variable with the value of a variable inside the loop. For example, the variable $id_puja is 767 at this loop item, when the user clicks on the button I want to create the session variable $_SESSION['clicked_puja'] = $row['id_puja'].

This is the button:

while{...
$id_puja = $row['id_puja'];
...
    <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
...
}

I EDITED, full loop code:

<?php
$resultadopujas=0;
global $mysqli;
$loop = mysqli_query($mysqli, "SELECT * FROM tb_pujas
    WHERE subasta_puja = '".$subasta."'")
or die (mysqli_error($mysqli));
$orden = 0;
$resultado = $loop ->num_rows;

if ($resultado == 0){

    ?>  <div class="container">
        <div class="jumbotron">
            <div class="row">
                <div class="col-md-6">


                    <p><?php echo $resultado."NO HAY PUJAS"?></p> 


                </div>
            </div>
        </div>
    </div>
    <?php
}
$numpuja=0;
while ($row = mysqli_fetch_array($loop))
    {$numpuja = $numpuja+1;
        $originalDate = $row['datetime_puja'];
        $newDate = date("d-m-Y H:i:s",strtotime($originalDate))
        ?>

        <div class="container">
            <div class="jumbotron" style="background-color: white">

                <div class="row">
                    <div class="col-md-2">

                        <img  style="width: 80px;height: auto;align-self: " src="garantia.png">
                    </div>
                    <div class="col-md-2">

                        <img  style="width: 80px;height: auto;align-self: " src="ok.png">
                    </div>
                    <div class="col-md-2">

                        <img  style="width: 80px;height: auto;align-self: " src="extra.png">
                    </div>


                    <div class="col-md-2">

                        <p><strong>Dia/Hora puja: </strong><?php echo $newDate?></p> 
                    </div>
                    <div class="col-md-2">

                        <p><strong>Precio puja: </strong><?php echo $row['precio_puja']." €"?></p> 
                    </div>
                    <div class="col-md-2">

                        <p><?php echo "<strong>Puja núm:</strong> ".$numpuja?></p> 
                    </div>


                </div>
                <div class="row">

                    <div class="col-md-12">

                        <p><?php echo "<strong>Comentarios:</strong> ".$row['comentarios_puja']?></p> 
                    </div>


                </div>

                <div class="row">
                    <div class="col-md-4">

                        <img  style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto1']?>">
                    </div>
                    <div class="col-md-4">

                        <img  style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto2']?>">
                    </div>
                    <div class="col-md-4">

                        <img  style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto3']?>">
                    </div>


                </div>
                <div class="row">
                    <div class="col-md-4">


                    </div>
                    <div class="col-md-4">

                    </div>
                    <div class="col-md-4">
                        <script>
                            function myclick(){
                                alert (<?php echo $row['precio_puja']?>);
                            }
                        </script>
                        <button type="button" class="btn btn-info btn-lg" data-toggle="modal" id="boton" onclick="myclick()" data-target="#myModal">Open Modal</button>

                    </div>


                </div>







            </div>
        </div>
    </div>




    <?php

}

?>

EDITED modal part

<div id="myModal" class="modal fade" role="dialog">



    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>




                <h4 class="modal-title">Mensajes de la subasta <?php echo $referencia."VAR=".$_COOKIE['puja']?></h4>
            </div>
            <div class="modal-body" style="background-color:#486A86; color: white">
                <div class="container">
                    <header class="header">
                        <h1>Chat</h1>
                    </header>
                    <main>
                        <img  src="images/logohorizontal.png" alt="Cribbeo" width="200px">
                        <div class="userSettings">
                            <label for="userName">Usuario: <?php echo $_SESSION['usuario']?></label>
                            <input id="userName" type="hidden" placeholder="Username" maxlength="32" value=" <?php echo $_SESSION['usuario']?>">
                        </div>
                        <div class="chat">
                            <div id="chatOutput"></div>
                            <input id="chatInput" type="text" style="background-color:white; color: #486A86" placeholder="Escribe aquí el texto de tu mensaje" maxlength="128">
                            <button id="chatSend" style="background-color:#486A86; color: white">Enviar</button>
                        </div>
                    </main>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
            </div>
        </div>

    </div>
</div>

And this is chat.js

$(document).ready(function() {
    var chatInterval = 250; //refresh interval in ms
    var $userName = $("#userName");
    var $chatOutput = $("#chatOutput");
    var $chatInput = $("#chatInput");
    var $chatSend = $("#chatSend");

    function sendMessage() {
        var userNameString = $userName.val();
        var chatInputString = $chatInput.val();

        $.get("./write.php", {
            username: userNameString,
            text: chatInputString
        });

        $userName.val("");
        retrieveMessages();
    }

    function retrieveMessages() {
        $.get("./read.php", function(data) {
            $chatOutput.html(data); //Paste content into chat output
        });
    }

    $chatSend.click(function() {
        sendMessage();
    });

    setInterval(function() {
        retrieveMessages();
    }, chatInterval);
});
11
  • 1
    You can achieve this with help of Ajax. Commented Jul 29, 2018 at 12:29
  • @Shivrudra, As test I have created an onclick function, but I always get the value from the last item in the loop, not from the selected item Commented Jul 29, 2018 at 12:31
  • 1
    @IncredibleHat, I have include the code with the loop, the button is at the bottom inside the loop Commented Jul 29, 2018 at 12:35
  • "I want to create the session variable $_SESSION['clicked_puja'] = $row['id_puja']." - That should work. Where did you try that? Assigning the session array to the looped row's id and then putting that back in where you want it should work. What difficulty are you having doing this? Commented Jul 29, 2018 at 12:36
  • 1
    I also can't see where $subasta is assigned in the WHERE clause. Does this have anything to do with all this? If so, then assign the session array to that, no? Commented Jul 29, 2018 at 12:39

1 Answer 1

1

Try this-

//START OF LOOP... 

//Add data-var attribute to your button to store the value of the session variable to be picked up by jQuery.
<button type="button" class="btn btn-info btn-lg session-btn" data-toggle="modal" data-target="#myModal" data-var="<?php echo $id_puja;?>">Open Modal</button>

//END OF LOOP..

// jQuery CDN link
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<script>
  $('.session-btn').on('click', function(){
  var session_var = $(this).data('var');
  console.log(session_var);  // prints the session variable value to the console.
  $(document).ready(checkModal);

  function checkModal() {
    if($('#myModal').is(':visible')){ 
      //if the modal is visible on the page

      $.ajax({
        url: 'read.php',
        type: 'POST',
        data: {session_var: session_var},
        success: function(){
          alert('success');
        }
      });
    }
  }
});
</script>

In read.php file

<?php 
  require("connect.php"); 
  session_start(): 

  //connect to db 
  $db = new mysqli($db_host,$db_user, $db_password, $db_name); 
  if ($db->connect_errno) { 
    //if the connection to the db failed 
    echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error; 
  } 

  if(isset($_POST['session_var'])){ 
    $_SESSION['session_var'] = $_POST['session_var'];
    echo $_SESSION['session_var'];

    $query="SELECT * FROM chat WHERE id_puja ='".$_SESSION['session_var']."' ORDER BY id ASC"; 
    //execute query 
    if ($db->real_query($query)) { 
      //If the query was successful 
      $res = $db->use_result(); 

      while ($row = $res->fetch_assoc()) { 
        $username=$row["username"]; 
        $text=$row["text"]; 
        $time=date('G:i', strtotime($row["time"])); //outputs date as # #Hour#:#Minute# 

        echo "<p>$time | $username: $text</p>\n"; 
      } 
    }else{ 
      //If the query was NOT successful 
      echo "An error occured"; 
      echo $db->errno; 
    } 
  } else {
    echo 'variable is not posted!';
  }
  $db->close(); 
?>
Sign up to request clarification or add additional context in comments.

1 Comment

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.