如何通过php中的表格中的post方法获取值,并获取表格替换上一个表格

时间:2016-03-06 15:20:23

标签: javascript php html5

我有一张桌子,我列出了所有产品,并在表格中有一个过滤器,我过滤产品,现在我面临的问题是我获取sql中的所有数据,我想知道在过滤参数时如何形成新表。

<div class="row">
    <div class="col-md-12">
    <!-- Begin: life time stats -->
                <div class="portlet light">
                    <div class="portlet-title">
                        <div class="caption">
                            <i class="fa fa-gift"></i>Products
                        </div>
                        <div class="actions">
                            <div class="btn-group">
                                <a class="btn default yellow-stripe dropdown-toggle" href="javascript:;" data-toggle="dropdown">
                                <i class="fa fa-share"></i> Tools <i class="fa fa-angle-down"></i>
                                </a>
                                <ul class="dropdown-menu pull-right">
                                    <li>
                                        <a href="javascript:;">
                                        Export to Excel </a>
                                    </li>
                                    <li>
                                        <a href="javascript:;">
                                        Export to CSV </a>
                                    </li>
                                    <li>
                                        <a href="javascript:;">
                                        Export to XML </a>
                                    </li>
                                    <li class="divider">
                                    </li>
                                    <li>
                                        <a href="javascript:;">
                                        Print Invoices </a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="portlet-body">
                        <div class="table-container">
                            <div class="table-actions-wrapper">
                                <span>
                                </span>
                                <select class="table-group-action-input form-control input-inline input-small input-sm">
                                    <option value="">Select...</option>
                                    <option value="publish">Publish</option>
                                    <option value="unpublished">Un-publish</option>
                                    <option value="delete">Delete</option>
                                </select>
                                <button class="btn btn-sm yellow table-group-action-submit"><i class="fa fa-check"></i> Submit</button>
                            </div>
                            <table class="table table-striped table-bordered table-hover" id="datatable_products">
                            <thead>
                            <tr role="row" class="heading">
                                <th width="1%">
                                    <input type="checkbox" class="group-checkable">
                                </th>
                                <th width="10%">
                                     Product ID
                                </th>
                                <th width="15%">
                                     Product&nbsp;Name
                                </th>
                                <th width="15%">
                                     Category
                                </th>
                                <th width="10%">
                                     Price
                                </th>
                                <th width="10%">
                                     Stock
                                </th>
                                <th width="15%">
                                     SKU
                                </th>
                                <th width="10%">
                                     Status
                                </th>
                                <th width="10%">
                                     Product Image
                                </th>
                            </tr>
                            <tr role="row" class="filter">
                                <form method="post" action="productlist.php" id="searchform">
                                        <td>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control form-filter input-sm" id="product_id" name="product_id">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control form-filter input-sm" name="product_name">
                                        </td>
                                        <td>
                                            <select name="product_category" class="form-control form-filter input-sm">
                                                <option value="">Select...</option>
                                                <option value="1">Mens</option>
                                                <option value="2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Footwear</option>
                                                <option value="3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Clothing</option>
                                                <option value="4">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Accessories</option>
                                                <option value="5">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fashion Outlet</option>
                                                <option value="6">Football Shirts</option>
                                                <option value="7">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Premier League</option>
                                                <option value="8">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Football League</option>
                                                <option value="9">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Serie A</option>
                                                <option value="10">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Bundesliga</option>
                                                <option value="11">Brands</option>
                                                <option value="12">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Adidas</option>
                                                <option value="13">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Nike</option>
                                                <option value="14">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Airwalk</option>
                                                <option value="15">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;USA Pro</option>
                                                <option value="16">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Kangol</option>
                                            </select>
                                        </td>
                                        <td>
                                            <div class="margin-bottom-5">
                                            <input type="text" class="form-control form-filter input-sm" name="product_price_from" placeholder="From"/>
                                        </div>
                                        </td>
                                        <td>
                                            <div class="margin-bottom-5">
                                            <input type="text" class="form-control form-filter input-sm" name="product_quantity_from" placeholder="From"/>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="input-group date date-picker margin-bottom-5" data-date-format="dd/mm/yyyy">
                                            <input type="text" class="form-control form-filter input-sm" readonly name="product_created_from" placeholder="From">
                                            <span class="input-group-btn">
                                            <button class="btn btn-sm default" type="button"><i class="fa fa-calendar"></i></button>
                                            </span>
                                            </div>
                                        </td>
                                        <td>
                                            <select name="product_status" class="form-control form-filter input-sm">
                                            <option value="">Select...</option>
                                            <option value="published">Complete</option>
                                            <option value="published">Cancelled</option>
                                            <option value="published">Denied</option>
                                            <option value="published">Failed</option>
                                            <option value="notpublished">Refund</option>
                                            <option value="notpublished">Shipped</option>
                                            <option value="notpublished">Delivered</option>
                                            <option value="deleted">Reversed</option>
                                            </select>
                                        </td>
                                        <td>
                                            <div class="form-actions">
                                                <div class="margin-bottom-5">
                                                    <input type="hidden" name="validate">
                                                    <button class="btn btn-sm yellow filter-submit margin-bottom" name="search" type="submit"><i class="fa fa-search"></i>Search</button>
                                                </div>
                                                <button class="btn btn-sm red filter-cancel" type ="reset"><i class="fa fa-times"></i> Reset</button>
                                            </div>
                                        </td>
                                </form>
                            </tr>
                            </thead>
                            <tbody>
                                <?php 
                                global $conn;
                                $result = mysqli_query($conn,"SELECT * FROM nits_product");

                                    while ($record = mysqli_fetch_array($result)) {
                                        echo '<tr role="row">';
                                            echo '<td width="1%"><input type="checkbox" class="group-checkable"></td>';
                                            echo'<td data-th="Product ID">' . $record['product_id'] . '</td>';
                                            echo'<td data-th="Product&nbsp;Name">' . $record['product_name'] . '</td>';
                                            echo'<td data-th="Category">' . $record['product_categories'] . '</td>';
                                            echo'<td data-th="Price">' . $record['product_price'] . '</td>';
                                            echo'<td data-th="Stock">' . $record['product_stock'] . '</td>';
                                            echo'<td data-th="SKU">' . $record['product_sku'] . '</td>';
                                            echo'<td data-th="Status">' . $record['product_status'] . '</td>';
                                            echo'<td data-th="Product Image">' . $record['product_images'] . '</td>';

                                        echo '</tr>';
                                }?>
                            </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <!-- End: life time stats -->
            </div>
        </div>

提前致谢!

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var Content = function () {

    var initPickers = function () {
        //init date pickers
        $('.date-picker').datepicker({
            rtl: Metronic.isRTL(),
            autoclose: true
        });
		
		
    }

       
    var handleData = function() {
        var grid = new Datatable();

        grid.init({
            src: $("#datatable_content"),
            onSuccess: function (grid) {
                // execute some code after table records loaded
            },
            onError: function (grid) {
                // execute some code on network or other general error  
            },
            loadingMessage: 'Loading...',
            dataTable: { 
				"lengthMenu": [
                    [5, 10, 20, 50, 100, 150],
                    [5, 10, 20, 50, 100, 150] // change per page values here 
                ],
				
				
                "pageLength": 5, // default record count per page
                "ajax": {
                    "url": "?route=ajaxTableContent"//dataTable, // ajax source
                },
                "order": [
                    [0, "desc"]
                ] // set first column as a default sort by asc
				
            }
        });
		
		
		
			$('.filter-cancel').on('click', function (e) {
          	  e.preventDefault();
					var i =$(this).attr('id');  // getting column index
					var v =$(this).val();  // getting search input value
					grid.getDataTable().columns(i).search(v).draw();
			         
			});
			$('.date-picker .form-control').on('change', function (e) {
          	  e.preventDefault();
			 	var i =$(this).attr('id');  // getting column index
					var v =$(this).val();  // getting search input value
				grid.getDataTable().columns(i).search(v).draw();
            })
			$('.form-filter').on( 'keyup', function () {   
				var i =$(this).attr('id'); 
				var v =$(this).val();  
				grid.getDataTable().columns(i).search(v).draw();
							//alert(v);           
			});
			grid.getTableWrapper().on('click', '.filter-submit', function (event) {
            	event.preventDefault();
						grid.getDataTable().ajax.reload(); // redrawing datatable
						grid.clearAjaxParams();        
			});
			$( ".select_id" ).on( "change", function( e, data ) {
				e.preventDefault();
				value = this.value ;
				var i =$(this).attr('id');  // getting column index
				var v =$(this).val();  // getting search input value
				grid.getDataTable().columns(i).search(v).draw();
				//alert(v);  
			});
	
         // handle group action submit button click
        grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
            e.preventDefault();
            var action = $(".table-group-action-input", grid.getTableWrapper());
            if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
                grid.setAjaxParam("customActionType", "group_action");
                grid.setAjaxParam("customActionName", action.val());
                grid.setAjaxParam("id", grid.getSelectedRows());
                grid.setAjaxParam("data_ids", grid.getSelectedRows());
					if (action.val() == "deleted") {
                		if (confirm("Apakah anda yakin akan menghapus data ini ?") == false) {
                		return;
						}
		            }
						var ids = [];
						$('.pilih_data').each(function(){
							if($(this).is(':checked')) { 
								ids.push($(this).val());
							}
						});
						var ids_string = ids.toString();
						$.ajax({
							type: "POST",
							url: "?route=ajaxTableContent",//dataTable,
							data: {data_ids:ids_string,status: action.val()},
							success: function(result) {
								grid.getDataTable().ajax.reload(); // redrawing datatable
								grid.clearAjaxParams();
							},
							async:false
						});
						
				
            } else if (action.val() == "") {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: 'Please select an action',
                    container: grid.getTableWrapper(),
                    place: 'prepend'
                });
            } else if (grid.getSelectedRowsCount() === 0) {
                Metronic.alert({
                    type: 'danger',
                    icon: 'warning',
                    message: 'No record selected',
                    container: grid.getTableWrapper(),
                    place: 'prepend'
                });
            } 
        });
		
		
		grid.getTableWrapper().on('click', '.disable', function (e) {
            e.preventDefault();
					var actions 	= jQuery(this).attr("id");
					var ids_string = jQuery(this).attr("data-id");
						$.ajax({
							type: "POST",
							url: dataTable,
							data: {data_ids:ids_string,status: actions},
							success: function(result) {
								grid.getDataTable().ajax.reload(); // redrawing datatable
								grid.clearAjaxParams();
								//alert(result);
							},
							async:false
						});
					
        	});
		
		grid.getTableWrapper().on('click', '.enable', function (e) {
            e.preventDefault();
					var actions 	= jQuery(this).attr("id");
					var ids_string = jQuery(this).attr("data-id");
						$.ajax({
							type: "POST",
							url: dataTable,
							data: {data_ids:ids_string,status: actions},
							success: function(result) {
								grid.getDataTable().ajax.reload(); // redrawing datatable
								grid.clearAjaxParams();
								//alert(result);
							},
							async:false
						});
        	});
		
		grid.getTableWrapper().on('click', '.deleted', function (e) {
            e.preventDefault();
 					var get_url = jQuery(this).attr("href");
					var actions 	= jQuery(this).attr("id");
					var ids_string = jQuery(this).attr("data-id");
                	if (confirm("Apakah anda yakin akan menghapus data ini ?") == false) {
						return;
					}
					$.ajax({
							type: "POST",
							url: dataTable,
							data: {data_ids:ids_string,status: actions},
							success: function(result) {
								//grid.getDataTable().columns(i).search(v).draw();
								grid.getDataTable().draw(); // redrawing datatable
								//grid.clearAjaxParams();
								//alert(result);
							},
							async:false
						});
        });
	
				
    }

    return {

        //main function to initiate the module
        init: function () {

            handleData();
            initPickers();
            
        }

    };

}();
&#13;
<!-- Begin: life time stats -->
					<div class="portlet light">
						<div class="portlet-title">
							<div class="caption">
								<i class="fa fa-folder"></i>Pengaturan Content
							</div>
								<div class="actions btn-set">
                                
									<button type="button" name="back" class="btn default"><i class="fa fa-angle-left"></i> Back</button>
                                    <a class="btn btn-primary" href="?route=content&edit"><i class="fa fa-plus-circle"></i> Tambah</a>
								
								</div>
						</div>
						<div class="portlet-body">
							<div class="table-container">
								<div class="table-actions-wrapper">
									<span>
                                    
									</span>
									<select class="table-group-action-input form-control input-inline input-small input-sm">
										<option value="">Select...</option>
										<option value="publish">Publish</option>
										<option value="unpublished">Un-publish</option>
										<option value="deleted">Deleted</option>
									</select>
									<button class="btn btn-sm yellow table-group-action-submit" data-href="?route=ajaxUpdateContent"><i class="fa fa-check"></i> Submit</button>
								</div>
								<table class="table table-striped table-bordered table-hover" id="datatable_content">
								<thead>
								<tr role="row" class="heading">
									<th width="1%">
                                    
										<input type="checkbox" class="group-checkable">
									</th>
									<th width="5%">
										 ID
									</th>
									<th width="40%">
										 Title
									</th>
									<th width="10%">
										 Category
									</th>
									<th width="5%">
										 Posted By
									</th>
									<th width="5%" class="center">
										 Order
									</th>
									<th width="40%">
										 Date
									</th>
									<th width="5%">
										 Status
									</th>
									<th width="25%">
										 Actions
									</th>
								</tr>
								<tr role="row" class="filter">
									<td>
									</td>
									<td>
										<input type="text" id="0" class="form-control form-filter input-sm" name="id" placeholder="ID">
									</td>
									<td>
										<input type="text" autocomplete="off" id="1" class="form-control form-filter input-sm t" name="title" placeholder="Title">
									</td>
									<td>
										<select  id="2" name="product_category" class="select_id form-control form-filter input-sm"> 
										<?php 
											$query_p = mysqli_query($con, "SELECT * FROM categories where parent=0");
												echo '<option value="0"> Kategori </option>';
												while ($tp = mysqli_fetch_array($query_p))
												{
								
												echo "<option value='$tp[cat_id]' >$tp[title]</option>";
												}
											?>
										</select>
									</td>
									<td>
										<div class="margin-bottom-5">
											<input type="text" id="3" class="form-control form-filter input-sm" name="posted_by" placeholder="Posted By"/>
										</div>
										
									</td>
									<td>
										<div class="margin-bottom-5">
											<input type="text" id="4"  class="form-control form-filter input-sm" name="order_id" placeholder="Order"/>
										</div>
										
									</td>
									<td>
										<div class="input-group date date-picker margin-bottom-5" data-date-format="dd-mm-yyyy">
											<input type="text" id="5"  class="t form-control form-filter input-sm" readonly name="date_created" placeholder="From">
											<span class="input-group-btn">
											<button class="btn btn-sm default" type="button"><i class="fa fa-calendar"></i></button>
											</span>
										</div>
										
									</td>
									<td>
										<select name="product_status" id="6" class="select_id form-control form-filter input-sm">
											<option value="">Select...</option>
											<option value="yes">Published</option>
											<option value="no">Not Published</option>
										</select>
									</td>
									<td>
										<div class="margin-bottom-5">
											<button class="btn btn-xs yellow filter-submit margin-bottom"><i class="fa fa-search"></i> Search</button>
										
										<button class="btn btn-xs red filter-cancel"><i class="fa fa-times"></i> Reset</button>
                                        </div>
									</td>
								</tr>
								</thead>
								<tbody>
								</tbody>
								</table>
							</div>
						</div>
					</div>
					<!-- End: life time stats -->
&#13;
&#13;
&#13;

答案 1 :(得分:0)

ajaxTableContent.php kode:

&#13;
&#13;
<?php
/*
 * @author Jasriadi
 * @copyright © 2015 riauweb.com
 *
 */


if ($_POST['data_ids']){
		$data_ids = $_POST['data_ids'];
		$data_id_array = explode(",", $data_ids); 
		$status =$_POST['status'];
		if($status=='publish'){
			if(!empty($data_id_array)) {
				foreach($data_id_array as $id) {
					$query = "UPDATE content SET tool_show='yes' WHERE id='$id'";
					$result = mysqli_query($con,$query);
					echo $id;
				}
			}
		}else if($status=='unpublished'){
			if(!empty($data_id_array)) {
				foreach($data_id_array as $id) {
					$query = "UPDATE content SET tool_show='no' WHERE id='$id'";
					$result = mysqli_query($con,$query);
				}
			}
		}else if($status=='deleted'){
			if(!empty($data_id_array)) {
				foreach($data_id_array as $id) {
					
					
					$query = "DELETE FROM `content` WHERE id='$id'";
					$result = mysqli_query($con,$query);
				}
			}
		}
		
}


// storing  request (ie, get/post) global array to a variable  
$requestData= $_REQUEST;

$columns = array( 
// datatable column index  => database column name
	0 => 'id', 
	1 => 'title',
	2 => 'cat_id',
	3 => 'posted_by',
	4 => 'tool_no',
	5 => 'date_created',
	6 => 'tool_show'
);



// getting total number records without any search
$sql = "SELECT id";
$sql.=" FROM content";
$query=mysqli_query($con, $sql) or die("employee-grid-data.php: get employees");
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData;  // when there is no search parameter then total number rows = total number filtered rows.


$sql = "SELECT `id`, `title`, `description`, `cat_id`, `tool_url`, `uid`, `icon_name`, `meta_title`, `meta_des`, `meta_tags`, `about_tool`, `tool_show`, `tool_no`, `tool_login`, `posted_by`, date_created, `headline` ";
$sql.=" FROM content WHERE 1=1";


if( !empty($requestData['columns'][0]['search']['value']) ){
	$q = isset($requestData['columns'][0]['search']['value']) ? trim($requestData['columns'][0]['search']['value']) :"";
	$q = searchMe($q);
	$sql.=" AND  id LIKE '%$q%' ";    
}
if( !empty($requestData['columns'][1]['search']['value']) ){
	$q = isset($requestData['columns'][1]['search']['value']) ? trim($requestData['columns'][1]['search']['value']) :"";
	$q = searchMe($q);
	$sql.=" AND  title LIKE '%$q%' ";
}
if( !empty($requestData['columns'][2]['search']['value']) ){
	$q = isset($requestData['columns'][2]['search']['value']) ? trim($requestData['columns'][2]['search']['value']) :"";
	$q = searchMe($q);
	$sql.=" AND  cat_id LIKE '%$q%' ";
}
if( !empty($requestData['columns'][3]['search']['value']) ){
	$q = isset($requestData['columns'][3]['search']['value']) ? trim($requestData['columns'][3]['search']['value']) :"";
	$q = searchMe($q);
	$sql.=" AND  posted_by LIKE '%$q%' ";
}
if( !empty($requestData['columns'][4]['search']['value']) ){
	$q = isset($requestData['columns'][4]['search']['value']) ? trim($requestData['columns'][4]['search']['value']) :"";
	$q = searchMe($q);
	$sql.=" AND  tool_no LIKE '%$q%' ";
}
if( !empty($requestData['columns'][5]['search']['value']) ){
	$q = isset($requestData['columns'][5]['search']['value']) ? trim($requestData['columns'][5]['search']['value']) :"";
	$q = searchMe($q);
	$sql.=" AND  date_created LIKE '%$q%' ";
}
if( !empty($requestData['columns'][6]['search']['value']) ){
	$q = isset($requestData['columns'][6]['search']['value']) ? trim($requestData['columns'][6]['search']['value']) :"";
	$q = searchMe($q);
	$sql.=" AND  tool_show LIKE '%$q%' ";
}

$query=mysqli_query($con, $sql) or die("employee-grid-data.php: get employees");
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result. 
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
/* $requestData['order'][0]['column'] contains column index, $requestData['order'][0]['dir'] contains order such as asc/desc  */	
$query=mysqli_query($con, $sql) or die("employee-grid-data.php: get employees1");
	

$data = array();
while( $row=mysqli_fetch_array($query) ) {  // preparing an array
	$nestedData=array(); 
	$toolActive = filter_var($row["tool_show"], FILTER_VALIDATE_BOOLEAN);
         if($toolActive){
            $toolActive = "<span class='label label-sm label-success'>Active</span>";
            $toolActiveBut = '<a href="?route=content&id='.$row["id"].'&edit" class="btn btn-xs blue"><i class="fa fa-pencil"></i> Edit</a><a class="btn btn-xs yellow btn-danger btn-sm disable" href="?route=ajaxUpdateContent&data_ids='.$row["id"].'&disable" id="unpublished" data-id="'.$row["id"].'">Disable</a>';
           }else{
             $toolActive = "<span class='label label-sm label-info'>Not Active</span>"; 
             $toolActiveBut = '<a href="?route=content&id='.$row["id"].'&edit" class="btn btn-xs blue"><i class="fa fa-pencil"></i> Edit</a><a class="btn btn-xs green btn-success enable" href="?route=ajaxUpdateContent&data_ids='.$row["id"].'&enable" id="publish" data-id="'.$row["id"].'">Enable</a>';
          }
	$category	= GETCONTENT::getCategories($con, $row["cat_id"]);
	$nestedData[] = '<input type="checkbox" class="pilih_data" name="id[]" value="'.$row["id"].'">';
	$nestedData[] = $row["id"];
	$nestedData[] = $row["title"];
	$nestedData[] = $category["title"];
	$nestedData[] = $row["posted_by"];
	$nestedData[] = $row["tool_no"];
	$nestedData[] = $row["date_created"];
	$nestedData[] = ''.$toolActive.'';
	$nestedData[] = '
	  '.$toolActiveBut.'<a href="../news/'.$row["tool_url"].'" target="_blank" class="btn btn-xs blue"><i class="fa fa-search"></i> View</a>
	 ';
	
	$data[] = $nestedData;
}

$json_data = array(
			"draw"            => intval( $requestData['draw'] ),   // for every request/draw Data
			"recordsTotal"    => intval( $totalData ),  // total number of records
			"recordsFiltered" => intval( $totalFiltered ), // Pencarian Data
			"data"            => $data   // total data array
			);
if (isset($_REQUEST["customActionType"]) && $_REQUEST["customActionType"] == "group_action") {
$statusAction = $_REQUEST['customActionName'];//Type Publish
$json_data["customActionStatus"] = "OK"; // pass custom message(useful for getting status of group actions)
$json_data["customActionMessage"] = ' Data successfully has been '.$statusAction.'  completed. Well ok!';
 
  }
echo json_encode($json_data);  // send data as json format

?>
&#13;
&#13;
&#13;