如何将java脚本变量传递给php

时间:2017-06-28 02:50:22

标签: php jquery

我试图从php->传递这个sid变量jquery / ajax - > php。所以,现在我已经创建了sid ='1',然后将其传递给jquery / ajax,然后我尝试将sid传递给code.php,以便在每次单击链接时进行数据库更新。但是,我无法在数据库中找到更新。请帮忙!

<body>
<a href="http://www.google.com" id="click">click here</a>
<?php
$sid='1';
?>
<script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
    $(document).ready(function(e){

    var sid=<?php echo $sid; ?>
    $('#click').click(function(event)
    {
        event.preventDefault(); 
        var request = $.ajax(
        {    
             type: "POST",
             url: "code.php",
             data:{source1:sid},
             success: function() {
                window.location.href = 'https://www.google.com/';
             }                               
        });
   });
});
</script>
</body>

这是code.php

<?php
// Connection to database
   $sid = $_POST['source1'];

  $conn=mysqli_connect("localhost","root","","sample");
  mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='$sid'");

  mysqli_close($conn);

?>

1 个答案:

答案 0 :(得分:0)

我认为这将是一个简单的尝试方法:

<body>
<a href="#" id="click">click here</a>
<?php
$sid='1';
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script type="text/javascript">
$( "#click" ).click(function() { 
var sid = <?php echo $sid ?>; // getting id from above
$.ajax({
       type: "POST", //post method
       url: "code.php",  //destination file
       data:"source1="+sid, // sending source1=sid the data
       success: function()
       {
     window.location.href = 'https://www.google.com/';
       },
     });
  });
  </script>
  </body>