简体   繁体   中英

How to get the id to set a session variable in php

This first part isn't having any issues now.

    <?php
  session_start();
  while($row = $result->fetch_assoc()){
    echo "<div id='name' style='margin-top:50px;'><h2>" . $row['name'] . "</h2>";
    echo "<a href='nextPage.php'><img class='pic' src='".$row['imageURL']."' data-id='".$row['id']."' height='100px'/></a></div>";
    echo "<div id='bio' style='border-bottom:1px solid #000;'><p>" . $row['bio'] . "</p></div>";
  }
?>

<script type="text/javascript">
  $(document).on('click', '.pic', function(){
    var id = $(this).data('id');
    $.ajax({
      type: 'POST',
      url: 'setSession.php',
      data: {myId: id}
    });
  });
</script>

After I click an image I just get php error messages telling me there is an undefined variable. I currently have 'setSession.php' as a separate page, not sure if it's supposed to be or not.

**Next Page**

    <?php
    session_start();
    include("connect.php");

    $result = mysqli_query($con, "select * from table");

    mysqli_close($con);
?>
<!doctype html>
<html>
    <head>
        <title></title>
    </head>

    <body>
      <div class="wrapper">
        <img src="<?php echo $row['imageURL'];?>" height="200px"/><br/>
        <div class="textSection" style="text-align:center;">
          <h2><?php echo $row['name'];?></h2>
          <p>
            <?php echo $row['bio'];?>
          </p>
        </div>
      </div>

    </body>
</html>

firstly, you should start session in that page like this.

session_start();

then access the session variable like this.

$_SESSION['your_key_here'];// this will return the value stored in session.

Put data attribute data-id on img tag and change ids into class since ids should be unique like so :

<img class='pic' src='" . $row['imageURL'] . "' data-id='" . $row['id'] . "' height='100px'/></a></div>";

And register click handler to img using its class together with AJAX request to set data id into session variable like so :

$(document).on('click', '.pic', function() {

   var id = $(this).data('id'); // get id value from data-id attribute
   $.ajax({
     type : 'POST',
     url : 'setSession.php',
     data : {
      myId : id
     },
     success : function(msg) { /* do something here for success request */ }
  });
});

Finally. in setSession.php page :

<?php
  session_start();
  $_SESSION['id'] = $_POST['myId']; // this come from ajax request
  echo "something"; // and this will available on ajax success callback
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM