如何使用POST通过重定向获取onclick和POST数据

时间:2017-04-29 07:35:23

标签: javascript php jquery html ajax

我正在使用ajax,javascript,php,还有新功能。

在这个场景中,当我点击该按钮时,我在index.html页面中有一个带onclick功能的按钮,我希望它在发布和id时将我重定向到另一个我的getdata.php页面。因此,当我被重定向到我的getdata.php页面时,我只需要使用该ID进行查询。

触发重定向的按钮位于index.html <button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>

我现在使用的以下代码。我希望我能在这里得到很多帮助。

的index.html

  <?php
session_start();
$conn = mysqli_connect("localhost","root","1234","a0");

?>
<!DOCTYPE html>
<html>
<head>
    <title></title> 
    <meta http-equiv="Cache-control" content="no-cache"> <!--The No-Cache-->
    <!--Bootstrap 3.3.7 CSS-->
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!--Data Tables-->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
    <!--Date Timepicker-->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <!--Linear Icons-->
    <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
    <!--Date Timepicker-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css">
</head>
<body>

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">MENU</button>
      <a class="navbar-brand" href="#"><span class="icon-bag"></span> SUPPLIER</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>


        <div class="container-fluid">
            <h2 >List of Machine</h2>
            <div class="table-responsive">
                <div align="right">
                    <button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-success">New File <span class="fa fa-code-fork"></span></button>
                </div>
                <br>
                <table id="user_data" class="table table table-bordered table-hover dt-responsive " width="100%">
                    <thead>
                        <tr>
                            <th width="5%">Image</th>
                            <th width="15%">Name</th>
                            <th width="10%">Date Added</th>
                            <th width="10%">Created By</th>
                            <th width="6%">Action</th>
                        </tr>
                    </thead>
                </table>

            </div>
        </div>
    </body>
</html>

<div id="userModal" class="modal fade">
    <div class="modal-dialog">
        <form method="post" id="user_form" enctype="multipart/form-data">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add New Business Type </h4>
                </div>
                <div class="modal-body">
                    <label>Business Name</label>
                    <input type="text" name="businessname" id="businessname" class="form-control" />
                    <br />
                    <label>Select Business Image</label>
                    <input type="file" name="businessimage" id="businessimage" />
                    <span id="user_uploaded_image"></span>
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="user_id" id="user_id" />
                    <input type="hidden" name="operation" id="operation" />
                    <input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){

    var dataTable = $('#user_data').DataTable({
        "processing":true,
        "serverSide":true,
        "order":[],
        "ajax":{
            url:"fetch.php",
            type:"POST"
        },
    });


    $(document).on('click', '.update', function(){
        var user_id = $(this).attr("id");
        $.ajax({
            url:"fetch_single.php",
            method:"POST",
            data:{user_id:user_id},
            dataType:"json",
            success:function(data)
            {
                $('#userModal').modal('show');
                $('#businessname').val(data.businessname);
                $('.modal-title').text("Update Business Type");
                $('#user_id').val(user_id);
                $('#user_uploaded_image').html(data.businessimage);
                $('#action').val("Save Changes");
                $('#operation').val("Edit");
            }
        })
    });

    $(document).on('click', '.delete', function(){
        var user_id = $(this).attr("id");
        if(confirm("Are you sure you want to delete this?"))
        {
            $.ajax({
                url:"delete.php",
                method:"POST",
                data:{user_id:user_id},
                success:function(data)
                {
                    alert(data);
                    dataTable.ajax.reload();
                }
            });
        }
        else
        { 
            return false;   
        }
    });

     function generatepdf() {

        var name = $(this).data('msid');        
        if (name != undefined && name != null) {
            window.location = 'reports/getdata.php';
            $.ajax({
                url:"reports/getdata.php",
                method:"POST"               
            });
        }
    };​


});
</script>

<!--Data Table JS-->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
</body>

fetch.php

<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM machine_supplier ";
if(isset($_POST["search"]["value"]))
{
    $query .= 'WHERE machine_description LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
    $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
    $query .= 'ORDER BY msid DESC ';
}
if($_POST["length"] != -1)
{
    $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
    $image = '';
    if($row["image1"] != '')
    {
        $image = '<img src="machine_images/'.$row["image1"].'" class="img-thumbnail" width="50" height="35" />';
    }
    else
    {
        $image = '';
    }
    $sub_array = array();
    $sub_array[] = $image;
    $sub_array[] = $row["machine_description"];
    $sub_array[] = $row["model_number"];
    $sub_array[] = $row["supplier"];

    $sub_array[] = '<select class="form-control">
                        <option selected disabled>YOUR ACTIONS</option>
                        <option name="update" id="'.$row["msid"].'"  class="update">UPDATE</option>
                        <option name="delete" id="'.$row["msid"].'"  class="delete">DELETE</option>
                    </select>
                    <button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
                    ';
    $data[] = $sub_array;
}
$output = array(
    "draw"              =>  intval($_POST["draw"]),
    "recordsTotal"      =>  $filtered_rows,
    "recordsFiltered"   =>  get_total_all_records(),
    "data"              =>  $data
); 
echo json_encode($output);
?>

function.php

<?php
function upload_image()
{
    if(isset($_FILES["image1"])) 
    {
        $extension = explode('.', $_FILES['image1']['name']);
        $new_name = rand() . '.' . $extension[1];
        $destination = 'machine_images/' . $new_name;
        move_uploaded_file($_FILES['image1']['tmp_name'], $destination);
        return $new_name;
    }
}

function get_image_name($user_id)
{
    include('db.php');
    $statement = $connection->prepare("SELECT image1 FROM machine_supplier WHERE msid = '$user_id'");
    $statement->execute();
    $result = $statement->fetchAll();
    foreach($result as $row)
    {
        return $row["image1"];
    }
}

function get_total_all_records()
{
    include('db.php');
    $statement = $connection->prepare("SELECT * FROM machine_supplier");
    $statement->execute();
    $result = $statement->fetchAll();
    return $statement->rowCount();
}

?>

访问getdata.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "databasename";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

if (isset($_POST['print'])) {
    $sql = "SELECT msid FROM machine_supplier WHERE";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            //data 
         }
    } else {
        echo "0 results";
    }
} else{
 //redirect back
}
?>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

简单的方法是不使用JS或Jquery满足您的要求。只需使用HTML表单和PHP,就像在index.php

中一样
<?php 
//In you index.php
//.....................
//..........................
//your other codes
//......................
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        ?>
        <form method="post" action="getdata.php">
            <input type="hidden" name="my_id" value="<?php echo $row['msid']; ?>" />
            <input type="submit" value="REDIRECT AND POST MY ID" />
        </form>
        <?php 
    }
} else {
    echo "0 results";
}

//.................
//.................

您只需使用此表单代码替换按钮代码,由于表单属性getdata.php,您的ID将被发布并重定向到action="getdata.php"页面。

请参阅表单方法post这意味着您的表单将使用POST方法提交。现在在getdata.php文件中执行以下操作

<?php
$posted_id = $_POST['my_id'];
echo $posted_id;
//now get data from DB using this id 
//get data from db where id = $posted_id

这不是getdata.php的完整代码,但您将使用此代码至少看到您发布的ID(从index.php到getdata.php)。有很多事情要做,比如检查http方法,错误处理等等。