user7843796
user7843796

Reputation:

How to get via onclick and POST data on redirect with POST

I'm working using ajax,javascript, php and still new with this.

Here the scenario, I have a button with onclick function in my index.html page when I click that button I want it to redirect me to another my getdata.php page while posting and id. So when I've been redirected to my getdata.php page I just need to query using that id.

The button that trigger redirection are located at index.html <button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>

The following codes I've been using right now. I hope I've got a lot of help right here.

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>

Upvotes: 0

Views: 2181

Answers (1)

BetaDev
BetaDev

Reputation: 4684

Easy way is not using JS or Jquery for your requirement. Just use HTML form and PHP only like following in your 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";
}

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

You just need to replace the button code with this form code and your ID will be posted and redirected to getdata.php page because of the form attribute action="getdata.php".

See the form method is post this means your form will be submitted using POST method. Now in your getdata.php file do following

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

This is not full code for getdata.php but you will see at least your posted id(from index.php to getdata.php) using this code. There are lots to do like checking http method, error handling etc etc.

Upvotes: 1

Related Questions