I am trying to create a jquery data table using php but I am receiving this error : DataTables warning: table id=document_table - Invalid JSON response.
Here is my code:
documents.php
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/dataTables.bootstrap4.min.css">
<title>Central American Management</title>
</head>
<body>
<div>
<input type="hidden" id="UserId" name="UserId" data-id="<?php echo($_SESSION['UserId'])?>"></input>
<div class="container-fluid">
<div class="row">
<div class="container">
<div class="btnAdd">
<button class="btn btn-primary btn-md" id="add-document"><i class="fa fa-plus " aria-hidden="true">
</i><span>Add Document</span></button>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<table id="document_table" class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Country</th>
<th>Shared</th>
<th>Uploaded BY</th>
<th>Uploaded Date</th>
<th>Options</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-container" id="modal-container"></div>
<script src="../javascriptfiles/Documents.js"></script>
</body>
</html>
Documents.js
$(document).ready(function(){
$.fn.dataTable.ext.errMode = function( settings, helpPage, message){
console.log(message);
};
$('#document_table').dataTable({
"fnCreatedRow": function( nRow, aData, iDataIndex ) {
$(nRow).attr('documentId', aData[0]);
},
'processing':true,
'serverSide':true,
'paging':'true',
'order' :[],
'ajax': {
'url': "//centralamericanmanagement.000webhostapp.com/phpfiles/getDocuments.php",
'type': "POST"
},
"columnDefs": [{
'target':[6],
'orderable' :false,
}]
});
});
server-side code
<?php
require_once '../DBConnection/dbConfig.php';
$sql = "SELECT * FROM `getDocuments`";
$temp = $dbh->query($sql);
$total_all_rows =$temp->fetchColumn() ;
if(isset($_POST['search']['value']))
{
$search_value = $_POST['search']['value'];
$sql .= " WHERE document_name like '%".$search_value."%'";
$sql .= " OR country_name like '%".$search_value."%'";
$sql .= " OR user like '%".$search_value."%'";
}
if(isset($_POST['order']))
{
$column_name = $_POST['order'][0]['column'];
$order = $_POST['order'][0]['dir'];
$sql .= " ORDER BY ".$column_name." ".$order."";
}
else
{
$sql .= " ORDER BY documentId desc";
}
if($_POST['length'] != -1)
{
$start = $_POST['start'];
$length = $_POST['length'];
$sql .= " LIMIT ".$start.", ".$length;
}
try {
$query = $dbh->query($sql);
$count_rows = $query->fetchColumn();
$data = array();
foreach($results as $row)
{
$sub_array = array();
$sub_array[] = $row["documentId"];
$sub_array[] = $row["document_name"];
$sub_array[] = $row["country_name"];
$sub_array[] = $row["shared"];
$sub_array[] = $row["user"];
$sub_array[] = $row["uploadDate"];
$sub_array[] = '<a href="javascript:void();" data-id="'.$row['documentId'].'" class="btn btn-info btn-sm editbtn" >Edit</a> <a href="javascript:void();" data-id="'.$row['documentId'].'" class="btn btn-danger btn-sm deleteBtn" >Delete</a>';
$data[] = $sub_array;
}
$output = array(
'draw'=> intval($_POST['draw']),
'recordsTotal' =>$count_rows ,
'recordsFiltered'=>$total_all_rows,
'data' => $data
);
echo json_encode($output);
}
catch (PDOException $e){
echo json_encode("Error!: " . $e->getMessage() . "<br/>");
}
?>
I have been looking at this for sometime now and after doing much research I am still not understanding where this error is coming from.
Related
hi this is my server side data table. I want to add individual column search option. when i want to search then the all search needs to filter with my search input.
here is my code.
the php code named with fetch.php connected with the database and its retrive the data from database.
<?php
$connect = new PDO("mysql:host=localhost;dbname=sbcldb_management", "sbcldb_management", "management_server2021");
$column = array('order_customer_name', 'order_item', 'order_date', 'order_value');
$query = '
SELECT * FROM tbl_order
WHERE order_customer_name LIKE "%'.$_POST["search"]["value"].'%"
OR order_item LIKE "%'.$_POST["search"]["value"].'%"
OR order_date LIKE "%'.$_POST["search"]["value"].'%"
OR order_value LIKE "%'.$_POST["search"]["value"].'%"
';
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY order_id DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$statement = $connect->prepare($query . $query1);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$total_order = 0;
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["order_customer_name"];
$sub_array[] = $row["order_item"];
$sub_array[] = $row["order_date"];
$sub_array[] = $row["order_value"];
$total_order = $total_order + floatval($row["order_value"]);
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT * FROM tbl_order";
$statement = $connect->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
'draw' => intval($_POST["draw"]),
'recordsTotal' => count_all_data($connect),
'recordsFiltered' => $number_filter_row,
'data' => $data,
'total' => number_format($total_order, 2)
);
echo json_encode($output);
?>
Here is the javascript code that calculate the subtotal. it shoul work with the individual search option.
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
$('#order_data tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
var dataTable = $('#order_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"ajax" : {
url:"fetch.php",
type:"POST"
},
drawCallback:function(settings)
{
$('#total_order').html(settings.json.total);
}
});
});
</script>
and this one is just a simple html formate.
<html>
<head>
<title>How to Get SUM with Datatable Server-side-processing in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container box">
<h3 align="center">How to Get SUM with Datatable Server-side-processing in PHP</h3>
<br />
<div class="table-responsive">
<table id="order_data" class="table table-bordered table-striped">
<thead>
<tr>
<th>Customer Name</th>
<th>Order Item</th>
<th>Order Date</th>
<th>Order Value</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th colspan="3">Total</th>
<th id="total_order"></th>
</tr>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
</tr>
</tfoot>
</table>
<br />
<br />
<br />
</div>
</div>
</body>
</html>
please help me doing this.
I have javascript function written within a "generate.php" script and I have "call.php" in a separate script. How do I add a button in "call.php"script that triggers a function in "generate.php"?
"generate.php": javascript; function called by 'save'
<?php
include_once("connection.php");
$chart_data = '';
$db = new dbObj();
$connString = $db->getConnstring();
$id=$_GET['id'];
$query = $connString->prepare("SELECT ID FROM Datas WHERE ID=?");
$query->bind_param('s',$id);
$query->execute();
$result=$query->get_result();
while($row = mysqli_fetch_array($result))
{
$chart_data .= "{ ID:'".$row["ID"]."'},";
}
echo $chart_data;
$chart_data = substr($chart_data, 0);
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP & Mysql</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas#1.0.0-rc.1/dist/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
</head>
<body>
<br /><br />
<div id="chart"></div>
<button id="save">Download</button>
<div class="container" style="width:900px;">
<h2 align="center">MySQL</h2>
<h3 align="center">Data</h3>
<br /><br />
<div id="bar-chart" data-colors="#29abe2,#ffc142,#1ab394, #FF0000, #FFFF00" ></div>
</body>
</html>
<script>
$("#save").click(function() {
html2canvas(document.getElementById('bar-chart')).then(canvas => {
var w = document.getElementById("bar-chart").offsetWidth;
var h = document.getElementById("bar-chart").offsetHeight;
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'pt', [w, h]);
doc.addImage(img, 'JPEG', 10, 10, w, h);
doc.save('xkey.pdf');
}).catch(function(e) {
console.log(e.message);
});
})
</script>
"call.php";
<?php
include_once("generate.php");
$connect = mysqli_connect("localhost", "root", "", "db01");
$output = '';
$sql = "SELECT * FROM Datas WHERE ID LIKE '%" .$_POST["search"]."%'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '<h4 align = "center">Search Result</h4>';
$output .= '<div class="table-responsive">
<table class = "table table bordered">
<tr>
<th>ID</th>
<th>Generate</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["ID"].'</td>
<td><button id="gen" name="generate" class="btn btn-primary"><i class="fa fa"" aria-hidden="true"></i>Generate</button></td>
</tr>
';
}
echo $output;
}
else
{
echo "Data not found";
}
?>
Your pos-PHP code must be located in same document. So either include it via <script src="generate.php"> or via <? require 'generate.php'; ?>
If you need the same functionality in separate scripts, you should extract your js function to a file. Don't forget to name it:
function giveItADescriptiveName() {
html2canvas(document.getElementById('bar-chart')).then(canvas => {
// etc
}).catch(function(e) {
console.log(e.message);
});
}
Then you can include that script in any file where you might need it:
<script src="path/to/where/you/saved/it/whatever-you-called-the-file.js"></script>
And ultimately, you pass your function as the handler:
<script>
$("#save").click(giveItADescriptiveName());
</script>
hi guys how can i create a validation so that when i import a csv file it will not give me a error offset(intentionally reduced the csv file column)
i got the code https://www.webslesson.info/2016/10/import-csv-file-data-into-mysql-database-using-php-ajax.html
here is the code in index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$query = "SELECT * FROM tbl_employee ORDER BY id desc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Import CSV File Data into MySQL Database using PHP & Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">Import CSV File Data into MySQL Database using PHP & Ajax</h2>
<h3 align="center">Employee Data</h3><br />
<form id="upload_csv" method="post" enctype="multipart/form-data">
<div class="col-md-3">
<br />
<label>Add More Data</label>
</div>
<div class="col-md-4">
<input type="file" name="employee_file" style="margin-top:15px;" accept=".csv"/>
</div>
<div class="col-md-5">
<input type="submit" name="upload" id="upload" value="Upload" style="margin-top:10px;" class="btn btn-info" />
</div>
<div style="clear:both"></div>
</form>
<br /><br /><br />
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="25%">Name</th>
<th width="35%">Address</th>
<th width="10%">Gender</th>
<th width="20%">Designation</th>
<th width="5%">Age</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["address"]; ?></td>
<td><?php echo $row["gender"]; ?></td>
<td><?php echo $row["designation"]; ?></td>
<td><?php echo $row["age"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#upload_csv').on("submit", function(e){
e.preventDefault(); //form will not submitted
$.ajax({
url:"import.php",
method:"POST",
data:new FormData(this),
contentType:false, // The content type used when sending data to the server.
cache:false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
if(data=='Error1')
{
alert("Invalid File");
}
else if(data == "Error2")
{
alert("Please Select File");
}
else if(data != 'Error1' && data != 'Error2')
{
$('#employee_table').html(data);
alert("Data Import Successfully");
}
}
})
});
});
</script>
and here is for import.php
<?php
if(!empty($_FILES["employee_file"]["name"]))
{
$connect = mysqli_connect("localhost", "root", "", "db");
$output = '';
$allowed_ext = array("csv");
$tmp = explode(".", $_FILES["employee_file"]["name"]);
$extension = end($tmp);
if(in_array($extension, $allowed_ext))
{
$file_data = fopen($_FILES["employee_file"]["tmp_name"], 'r');
fgetcsv($file_data);
while($row = fgetcsv($file_data))
{
$id = mysqli_real_escape_string($connect, $row[0]);
$name = mysqli_real_escape_string($connect, $row[1]);
$address = mysqli_real_escape_string($connect, $row[2]);
$gender = mysqli_real_escape_string($connect, $row[3]);
$designation = mysqli_real_escape_string($connect, $row[4]);
$age = mysqli_real_escape_string($connect, $row[5]);
$query = "
INSERT INTO tbl_employee
(id,name, address, gender, designation, age)
VALUES ('$id','$name', '$address', '$gender', '$designation', '$age')
";
mysqli_query($connect, $query);
}
$select = "SELECT * FROM tbl_employee ORDER BY id DESC";
$result = mysqli_query($connect, $select);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="25%">Name</th>
<th width="35%">Address</th>
<th width="10%">Gender</th>
<th width="20%">Designation</th>
<th width="5%">Age</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["designation"].'</td>
<td>'.$row["age"].'</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
else
{
echo 'Error1';
}
}
else
{
echo "Error2";
}
?>
i put all the code so that every one can try it too.
Thanks for answer
please help me.. i am having a trouble with the popup modal.. how to get a certain data/value and display it to the modal.. I dynamically fetch a data from database and display it to html form, when i clicked one of the displayed item the modal popup should show containing the said description. My problem is that when I clicked one of the items it popup the modal but it contains all the data that is not related to the item that i Clicked.
Example i fetched form database this 2 items below (see pictures below),
when i clicked one of them the popup modal should show containing the said value like below
but i am having a trouble when i clicked one of them it show all the description with the other item like below
my code is here
<script type="text/javascript">
$(function () {
$("#btnShow").click(function(){
$.ajax({
url: 'prologue.php?story=$row[title]',
method: 'get',
success: function(data) {
$(".modal-body").html(data);
},
error:function(xhr,code,text){
alert("error occoured : "+text);
}
});
$('#demoModal').modal('show');
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<title>Compiled Story</title>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="../js/js/bootstrap.min.js"></script>
<link href="../js/js/bootstrap.min.css" rel="stylesheet" >
<link rel="stylesheet" href="app.css">
<link rel="stylesheet" href="../css/font-awesome.min.css">
<link rel="shortcut icon" href="../logo.png">
</head>
<body>
<table class="story-albums-lib" style="margin-left: 250px;">
<?php
$con=mysqli_connect("localhost","root","","scenezone");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM create_story
WHERE title IN (SELECT story FROM story_chapter WHERE status = '1');";
$result=mysqli_query($con,$sql);
// Fetch all
$i = 0;
while($row = mysqli_fetch_array($result)){
if ($i % 5 == 0) {
echo "<tr>";
}
echo "<td><a href='prologue.php?story=$row[title]'><img src='../stories/" .$row['image']."' alt='Image' id='btnShow' style='width: 200px; height: 250px; border-radius: 8px;'></a>
<br><p id='btnShow' style='margin-left:50px;'>".$row["title"]."</p>
</td>";
if ($i % 5 == 4) {
echo "</tr>";
}
$i++;
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
</div>
<!-- Modal -->
<div class="modal fade" id="demoModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"><?php echo $row ['email'];?></h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnchapterlist" class="btn btn-primary">Start Reading</button>
</div>
</div>
</div>
</div>
</table>
</div>
</body>
</html>
here is my prologue.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "scenezone";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM create_story
WHERE title IN (SELECT story FROM story_chapter WHERE status = '1');";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<center>";
echo "<tr>";
echo "<td><img src='../stories/".$row['image']."' alt='Image' class='img-responsive;' style='width: 200px; height: 250px;'>
<br><p> Title: ".$row["title"]."
<br>Genre : ".$row["genre"]."
<br>Author : ".$row["pen_name"]."
<br>Prologue : ".$row["description"]."</p>
</td>";
echo "</tr>";
echo "</center>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Did you have tried to use a foreach() or a for() loop to populate your modal?
Consider also to use an $.each() inside the success function of your ajax request.
EDIT: As requested here is how i will try to fetch the needed data, I will not include the prepared statements, this is not a problem during the develop of your page, but you need to implement them in the release version for security reason.
<?php
$con=mysqli_connect("localhost","root","","scenezone");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM create_story
WHERE title IN (SELECT story FROM story_chapter WHERE status = '1');";
$result=mysqli_query($con,$sql);
// Fetch all
foreach($result as $row):
$title = $row[title];
$email = $row['email'];
$image = $row['image'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Compiled Story</title>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="../js/js/bootstrap.min.js"></script>
<link href="../js/js/bootstrap.min.css" rel="stylesheet" >
<link rel="stylesheet" href="app.css">
<link rel="stylesheet" href="../css/font-awesome.min.css">
<link rel="shortcut icon" href="../logo.png">
</head>
<body>
<table class="story-albums-lib" style="margin-left: 250px;">
</div>
<!-- Modal -->
<div class="modal fade" id="demoModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"><?php echo $email; ?></h4>
</div>
<div class="modal-body">
<tr>
<td><a href='prologue.php?story=<? echo $title; ?>'>
<img src='../stories/" .<? echo $image; ?>."' alt='Image' id='btnShow' style='width: 200px; height: 250px; border-radius: 8px;'></a>
<br><p id='btnShow' style='margin-left:50px;'>".<? echo $title ?>."</p>
</td>
</tr>
<? endforeach;
mysqli_free_result($result);
mysqli_close($con);?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnchapterlist" class="btn btn-primary">Start Reading</button>
</div>
</div>
</div>
</div>
</table>
</div>
</body>
</html>
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">×</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>
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.