将价值从JS传递到PHP

时间:2018-12-14 03:40:30

标签: javascript php jquery

将表格单元格值从javascript变量传递到php变量。

<script>
  $(document).on('ready',function(){
    $('#business_list_table').on('click','.view_btn',function (){
      $.ajax({
      url: "test.php",
      method: "POST",
      data:{business_id : "6510-1"},
      success: function (data){
        $('#business_permit_table').html(data);
        }
      });
    });
  });

<?php
$business_id = $_GET["business_id"];
echo $business_id;

2 个答案:

答案 0 :(得分:2)

您不能像这样直接将JS变量直接用于PHP。改用ajax:

JS

$("#business_list_table").on('click', '.view_btn', function post() {
    // get the current row
    var currentRow = $(this).closest("tr");
    var Business_id_value= currentRow.find("td:eq(1)").text(); // get current row 2nd T;

    $.post('', {Business_ID: Business_id_value}, function(result){
        $('table tbody').html(result);
    });

});

PHP

if (isset($_POST['Business_ID'])) {
    $Business_ID = $_POST['Business_ID'];

    $conn = mysqli_connect("localhost", "root", "", "bpsystem");
    if ($conn->connect_error) {
        die("Database connection failed:" . $conn->connect_error);
    } else {
        $sql = "SELECT * FROM business_tb WHERE Business_ID='$Business_ID';";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            // output data of each row
            while ($row = $result->fetch_assoc()) {
                echo "<tr >";
                echo "<td>BUSINESS NAME</td>";
                echo "<td>" . $row['Business_Name'] . "</td>";
                echo "</tr>";
                echo "<tr >";
                echo "</tr>";
            }
        }
    }
}

答案 1 :(得分:0)

您可以使用查询字符串将变量传递给PHP。像这样

$("#business_list_table").on('click', '.view_btn', function post() {
    // get the current row
    var currentRow = $(this).closest("tr");
    var Business_id_value= currentRow.find("td:eq(1)").text(); // get current row 2nd T;
    window.location.href = 'http://your_url?b_id=' + Business_id_value;

});

现在,您可以使用$_GET['Business_id_value']

在PHP脚本中访问 Business_id_value 变量