简体   繁体   中英

Passing value from JS to PHP

Passing a table cell value from javascript variable into php variable.

<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; 

You cannot use JS variable directly to PHP like that. use ajax instead:

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>";
            }
        }
    }
}

You can use the query string to pass the variable to PHP. Like this,

$("#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;

});

Now you can access the Business_id_value varible in your PHP script using $_GET['Business_id_value']

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