-2

I want to pass a PHP variable to Jquery AJAX. How can I achieve this? I tried the below script.

$query_sess="select id from users where username='".$_SESSION['username']."'";
$result_sess = mysqli_query($con,$query_sess) or die('error');
$row_sess= mysqli_fetch_assoc($result_sess);
$userID = $row_sess['id'];

I need to pass this $userID to the ajax. My ajax script is as follows:

$(document).ready(function(){

    function load_unseen_notification(view = '')
    {
     $.ajax({
      url:"fetch_notification.php",
      method:"POST",
      data:{view:view, userID: <?php echo $userID; ?>},
      dataType:"json",
      success:function(data)
      {
       $('.dropdown-menunot').html(data.notification);
       if(data.unseen_notification > 0)
       {
        $('.count').html(data.unseen_notification);
       }
      }
     });
    }
Sanju Menon
  • 625
  • 1
  • 6
  • 16

1 Answers1

0

The PHP script can put the user ID into a global variable, which could be accessed from the JavaScript.

$query_sess="select id from users where username='".$_SESSION['username']."'";
$result_sess = mysqli_query($con,$query_sess) or die('error');
$row_sess= mysqli_fetch_assoc($result_sess);
$userID = $row_sess['id'];
?>
<script>
var userID = <?php echo $userID; ?>;
</script>

Then in the AJAX call you can refer to that variable.

      data:{view:view, userID: userID},
Barmar
  • 741,623
  • 53
  • 500
  • 612