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>
Related
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.
Hi i want to ask about my problem, so in my case i want to show a modal from "Edit" button and then the modal get data from database based on id. This is my code and still didn't work. Can you tell me where i missing it?
tokoCrud.php
<?php
include ('crudAction.php');
function insertData($db, $tableName) {
$data = [
'id_ot' => ' ',
'nama_ot' => $_POST['namaToko'],
'alamat_ot' => $_POST['alamatToko'],
'status_ot' => '1'
];
if(!isDataTokoExist($db, $namaToko)) {
session_start();
include ('logger.php');
$query = buildInsertQuery($tableName, $data);
$idTarget = 'Master Barang';
$data = ['username_pstr' => $_SESSION['username'], 'Create' => 'DataToko'];
writeLogToko($db, $_SESSION['idpengguna'], $idTarget, 'Toko', 'Insert Data Toko', $data);
return runQuery($db, $query, 'insert');
}
else {
header('location: ' . $_REQUEST['pageReferrer'] . '&error=false&message=' . $result['message']);
}
}
function updateData($db, $tableName) {
$data = [
'id_ot' => ' ',
'nama_ot' => $_POST['namaToko'],
'alamat_ot' => $_POST['alamatToko']
];
if(isset($_GET['idToko'])) {
$tokoId = $_GET['idToko'];
}
$query = buildUpdateQuery($tableName, $data);
$query .= " WHERE id_ot = '$tokoId' ";
return runQuery($db, $query, 'update');
}
function isDataTokoExist($db, $namaToko) {
$namaToko = $_POST['namaToko'];
$query = "SELECT * FROM master_toko WHERE nama_ot = '$namaToko'";
$result = mysqli_query($db, $query);
return $result -> num_rows > 0;
}
function getDataToko() {
$db = getDBConnection();
$query = "SELECT * FROM master_toko ORDER BY id_ot DESC";
$result= mysqli_query($db, $query);
return $result;
}
function getDetailToko($db, $tableName) {
$tokoId = $_GET['idToko'];
$query = "SELECT * FROM $tableName WHERE id_ot = $tokoId";
$result = runQuery($db, $query, 'select');
return mysqli_fetch_array($result['data'], MYSQLI_ASSOC);
}
?>
This is endpoint.php
<?php
$action = $_GET['action'];
$objectType = $_GET['objectType'];
$db = getDBConnection();
$tableName = getTableName($objectType);
$return = [];
if ($objectType === 'toko') {
include 'tokoCrud.php';
if ($action === 'get') {
$return = getDetailToko($db, $tableName);
}
}
return json_encode($return);
die();
?>
This is formAction.php
<?php
$actionObject = $_REQUEST['actionObject'] ?? '';
$actionType = $_REQUEST['actionType'] ?? '';
include $actionObject .'Crud.php';
include 'config.php';
function getTableName($actionObject)
{
$tableMapping = [
'toko' => 'master_toko'
// 'barang' => 'table_barang',
// 'jenis' => 'table_jenis',
];
return $tableMapping[$actionObject];
}
$db = getDBConnection();
$tableName = getTableName($actionObject);
switch($actionType):
case 'insert' : $result = insertData($db, $tableName);
break;
case 'delete' : $result = deleteData($db, $tableName);
break;
case 'update' : $result = updateData($db, $tableName);
break;
endswitch;
if (!$result['error']) {
header('location: ' . $_REQUEST['pageReferrer'] . '&error=false&message=' . $result['message']);
} else {
header('location: ' . $_REQUEST['pageReferrer'] . '&error=true&message=' . $result['message']);
}
?>
This is crudAction.php
<?php
function runQuery($db, $query, $queryType) {
$result = mysqli_query($db, $query);
if(!empty(mysqli_error($db))) {
return [
'error' => true,
'message' => mysqli_error($db)
];
}
return [
'error' => false,
'message' => getMessage($queryType),
'data' => $result
];
}
function buildInsertQuery($tableName, $data) {
$tableColumns = [];
$insertValues = [];
foreach ($data as $key => $value) {
array_push($tableColumns, $key);
array_push($insertValues, $value);
}
$columns = "(`" . implode("`,`", $tableColumns) . "`)";
$values = "('" . implode("','", $insertValues) . "')";
$query = "INSERT INTO `$tableName` ". $columns . " VALUES " . $values ." ";
return $query ?? false;
}
function buildUpdateQuery($tableName, $data) {
$tableColumns = [];
$insertValues = [];
foreach ($data as $key => $value) {
array_push($tableColumns, $key);
array_push($insertValues, $value);
}
$columns = "(`" . implode("`,`", $tableColumns) . "`)";
$values = "('" . implode("','", $insertValues) . "')";
$query = "UPDATE `$tableName` SET ". $columns ." = " .$values ." ";
return $query ?? false;
}
function getMessage($queryType) {
$messages = [
'insert' => 'Data has been succesfuly added',
'update' => 'Data has been succesfuly updated',
'delete' => 'Data has been succesfuly deleted',
'select' => 'Data has been selected',
'dataDouble' => 'Data Ada yang Dobel'
];
return $messages[$queryType];
}
function getLastID() {
return mysqli_insert_id();
}
?>
This is master_toko.php
<?php
require "partial/header.php";
require "partial/sidebar.php";
include ('library/services/tokoCrud.php');
// include 'messageBox.php';
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1>Master Toko</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Master Toko</li>
</ol>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<!-- Main content -->
<section class="content">
<?php include 'library/services/messageBox.php';
?>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Data Toko</h3>
<button type="button" class="btn btn-success float-right" data-toggle="modal" data-target=".modalBesar">Tambah Data</button>
</div>
<!-- Bagian Form Modal -->
<div class="modal fade modalBesar" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">Tambah Toko</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method = "post" action = "library/services/formAction.php">
<input type="hidden" name="pageReferrer" value="http://localhost/city/?page=store" >
<input type="hidden" name="actionObject" value="toko" >
<input type="hidden" name="actionType" value="insert" >
<div class="form-group">
<label for="recipient-name" class="col-form-label">Nama Toko</label>
<input type="text" class="form-control" id="namaToko" placeholder="Masukkan Nama Toko" name="namaToko" required>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Alamat Toko</label>
<input type="text" class="form-control" id="alamatToko" placeholder="Masukkan Nama Toko" name="alamatToko" required>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Akhir Bagian Modal -->
<!-- Bagian Edit Form Modal -->
<div class="modal fade modalBesar" tabindex="-1" role="dialog" aria-hidden="true" id = "modalUpdate">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel">Edit Data Toko</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method = "post" action = "library/services/formAction.php">
<input type="hidden" name="pageReferrer" value="http://localhost/city/?page=store" >
<input type="hidden" name="actionObject" value="toko" >
<input type="hidden" name="actionType" value="update" >
<input type="hidden" name="action" value="get" >
<input type="hidden" name="idToko" value="<? $idToko; ?>" >
<div class="form-group">
<label for="recipient-name" class="col-form-label">Nama Toko</label>
<input type="text" class="form-control" id="namaToko" placeholder="Masukkan Nama Toko" name="namaToko" required>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Alamat Toko</label>
<input type="text" class="form-control" id="alamatToko" placeholder="Masukkan Nama Toko" name="alamatToko" required>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Akhir Edit Bagian Modal -->
<!-- /.card-header -->
<div class="card-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>No</th>
<th>Toko</th>
<th>Alamat</th>
<th>Status</th>
<th>Opsi</th>
</tr>
</thead>
<tbody>
<?php
$n=1;
$toko = getDataToko();
while ($dataToko = mysqli_fetch_array($toko)) {
if($dataToko['status_ot']==1)
{
$status = "Aktif";
$idStatus = "1";
}
if($dataToko['status_ot']==2)
{
$status = "Tidak Aktif";
$idStatus = "2";
}
?>
<tr>
<td>
<?php echo $n++; ?>
</td>
<td>
<?php echo $dataToko['nama_ot'] ?>
</td>
<td>
<?php echo $dataToko['alamat_ot'] ?>
</td>
<td>
<?php echo $status ?>
</td>
<td>
<button type = "button" class = "view-detail btn btn-success"> Edit </button>
<button type = "button" class = "btn btn-danger deletebtn"> Delete </button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- /.content-wrapper -->
<?php require "partial/footer.php"; ?>
<script>
let buttonDetail = document.querySelectorAll('.view-detail');
buttonDetail.forEach((function(_el)) {
_el.addEventlistener('click', function(e) {
var modal = _el.getAttribute("modalBesar");
let idToko = e.target.dataset.id;
$.ajax ({
url: 'http://localhost/city/library/services/endpoint.php',
method: 'POST',
data: {action: 'get', objectType: 'toko', idToko: 'idToko'},
dataType: 'json',
success : function(response) {
let namaToko = response.namaToko;
let alamatToko = response.alamatToko;
}
});
});
});
</script>
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.
i am facing some kind of issue here in my javascript i think, it was working to open a small windows, but i don't know how it's not working now. here's below my javascript code ad my php and html codes
<?php
require_once '../core/init.php';
$id = $_POST['id'];
if(is_numeric($id) && $id > 0 && $id == round($id, 0)){
$id = $_POST['id'];
} else {
exit;
}
$id = (int)$id;
$sql = "SELECT * FROM products WHERE id = '$id'";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
$brand_id = $product['brand'];
$sql = "SELECT brand FROM brand WHERE id = '$brand_id'";
$brand_query = $db->query($sql);
$brand = mysqli_fetch_assoc($brand_query);
$sizestring = $product['sizes'];
$size_array = explode(',', $sizestring);
?>
<!-- Details Modal -->
<?php ob_start(); ?>
<div class="modal fade details-1" id="details-modal" tabindex="-1" role="dialog" aria-labelledby="details-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" onclick="closemodal()" aria-label="close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title text-center"><?php echo $product['title']; ?></h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-sm-6">
<div class="center-block">
<img src="<?php echo $product['image']; ?>" alt="<?php echo $product['title']; ?>" class="details img-responsive">
</div>
</div>
<div class="col-sm-6">
<h4>Details</h4>
<p><?php echo $product['description']; ?></p>
<hr>
<p>Price: $<?php echo $product['price']; ?></p>
<p>Brand: <?php echo $brand['brand']; ?></p>
<form action="add_cart.php" method="post">
<div class="form-group">
<div clss="col-xs-3">
<label for="quantity">Quantity:</label>
<input type="text" class="form-control" id="quantity" name="quantity">
</div>
</div>
<div class="form-group">
<label for="size">Size:</label>
<select name="size" id="size" class="form-control">
<option value=""></option>
<?php foreach($size_array as $string) {
$string_array = explode(':', $string);
$size = $string_array[0];
$quantity = $string_array[1];
echo '<option value="'.$size.'">'.$size.' ('.$quantity.' Available)</option>';
} ?>
</select>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" onclick="closemodal()">Close</button>
<button class="btn btn-warning" type="submit"><span class="glyphicon glyphicon-shopping-cart"></span>Add To Cart</button>
</div>
</div>
</div>
</div>
<script>
function closemodal(){
jQuery ('#details-modal').modal('hide');
setTimeout(function(){
jQuery('#details-modal').remove();
jQuery('.modal-backdrop').remove();
},500);
}
</script>
<?php echo ob_get_clean(); ?>
After looking at your var_dump($product); result:
array(10) {
["id"]=> string(1) "1"
["title"]=> string(12) "Levi's Jeans"
["price"]=> string(5) "29.99"
["list_price"]=> string(5) "39.99"
["band"]=> string(1) "1"
["categories"]=> string(1) "6"
["image"]=> string(24) "images/products/men4.png"
["description"]=> string(16) "Description here"
["featured"]=> string(1) "1"
["sizes"]=> string(14) "28:3,32:2,36:5"
}
It's obvious that you do not have a field named 'brandin yourproducts` table.
The nearest field name to brand is band which I think is a typo. So if you change this line of your code:
`$brand_id = $product['brand'];`
To this
`$brand_id = $product['band'];`
Then you will solve the error
Notice: Undefined index: brand
And in this query $sql = "SELECT * FROM products WHERE id = '$id'"; since $id is integer, there is no need to enclose it in single quotes and you can have your query like this:
$sql = "SELECT * FROM products WHERE id = $id";
Also looking at your queries, you have two queries which you can combine them to a single query using a simple join
You have `"SELECT * FROM products WHERE id = '$id'" and "SELECT brand FROM brand WHERE id = '$brand_id'"
In table products, the field band is foreign key to table brand field id So you can simply write this query:
$sql = "SELECT products.*, brand.brand FROM products left join brand on products.band = brand.id WHERE products.id = $id";
So your php section at the top of your detailsmodal.php file will become like this:
<?php
require_once '../core/init.php';
$id = $_POST['id'];
if(is_numeric($id) && $id > 0 && $id == round($id, 0)){
$id = $_POST['id'];
} else {
exit;
}
$id = (int)$id;
$sql = "SELECT products.*, brand.brand FROM products left join brand on products.band = brand.id WHERE products.id = $id";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
$sizestring = $product['sizes'];
$size_array = explode(',', $sizestring);
?>
and then only at this line of your html:
<p>Brand: <?php echo $brand['brand']; ?></p>
You have to change it to
<p>Brand: <?php echo $product['brand']; ?></p>
Note: Since you are using mysqli, It's highly advised to use prepared statements instead of just putting your variable directly in your query
I've been trying to dynamically create a modal view in a table.
The data used to create the table is comming from a sql database.
Now my problem:
Whenever I click on a button called "Details" the modal view is opening and contains the data it should.
However, when I try to close the view with the "Close"- Button or the X in the top right corner the modal view will close for a second and reopen on its own.
The background will get darker after I do one of the above mentioned operations.
Here comes the tricky part. Whenever I close the view with the escape button on my keyboard, it'll close as it should and I'll get back to my previous view.
<?php
mysql_connect("localhost", "****" , "****");
mysql_select_db("hallo");
$sql= "SELECT * FROM erfassung WHERE Status='Abgeschlossen'";
$query=mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($query)) {
$thisId = $row['id'];
$thisModalId = 'modal'.$thisId;
$thisModalIdHref = '#'.$thisModalId;
$thisFormDoneId = $row['id'].'FormDoneId';
// Create table row
echo "<tr onclick=\"input\" data-toggle=\"modal\" href='$thisModalIdHref'>";
echo "<td>";
echo $row['Name'];
echo "<td>";
echo $row['Betreff'];
echo "<td>";
echo "<button class=\"btn btn-primary btn-lg\" data-toggle=\"modal\" data-target='$thisModalIdHref'>";
echo "Details";
echo "</button>";
echo"<div class=\"modal fade\" id='$thisModalId' tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">";
echo "<div class=\"modal-dialog\">";
echo "<div class=\"modal-content\">";
echo "<div class=\"modal-header\">";
echo "<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>";
echo "<h4 class=\"modal-title\" id=\"myModalLabel\">Weitere Information </h4>";
echo "</div>";
echo"<div class=\"modal-body\">";
echo "<dl class=\"dl-horizontal\">";
echo "<dt>Bereich</dt>";
echo "<dd>" .$row['Bereich']. "</dd>";
echo "</dl>";
echo"</div>";
echo"<div class=\"modal-footer\">";
echo "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>";
echo "<button type=\"button\" class=\"btn btn-primary\">Save changes</button>";
echo"</div>";
echo"</div>"; //<!-- /.modal-content -->
echo"</div>";//<!-- /.modal-dialog -->
echo"</div>";//<!-- /.modal -->
echo "</td>";
echo "</tr>";
}
?>
For clarification:
If the $thisModalId is changed to the previous "MyModal" it works, but the button will, as it's supposed to, open the same text.
If you need any more source code or something else, I'd be more than happy to post it.
Thanks in advance for your help guys.
Best regards.
This is probably caused by the fact that your modal div is defined inside the element (tr) that the onclick handler is defined on. If the close button handler does not consume the click event, it will bubble to the containing elements all the way up (div, div, div, div, td, tr). When it gets to the tr, the onclick handler will execute and the modal will open again.
Obviously, you can solve this by not having your modal div inside your table structure, which doesn't really have a function anyway. This means that you will have to perform more than one separate loop, because the divs have to be all the way outside the table. This does not have to mean that your code will get messy if you take the advice of some of the commenters above and separate your PHP from your HTML a little bit.
Try something like this:
<?php
// Collect data
mysql_connect("localhost", "****" , "****");
mysql_select_db("hallo");
$sql= "SELECT * FROM erfassung WHERE Status='Abgeschlossen'";
$query=mysql_query($sql) or die (mysql_error());
$modals = array();
while($row = mysql_fetch_assoc($query)) {
$modals[] = array(
'id' => 'modal' . $row['id'],
'href' => '#modal' . $row['id'],
'FormDoneId' => $row['id'] . 'FormDoneId',
'Name' => $row['Name'],
'Betreff' => $row['Betreff'],
'Bereich' => $row['Bereich'],
);
}
?>
<table> <!-- Or something -->
<?php
foreach ($modals as $modal) {
// Create table rows
?>
<tr onclick="input" data-toggle="modal" href="<?php echo $modal['href'] ?>">
<td>
<?php echo $modal['Name'] ?>
<td>
<?php echo $modal['Betreff'] ?>
<td>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="<?php echo $modal['href'] ?>">
Details
</button>
</td>
</tr>
<?php
}
?>
</table>
<?php
foreach ($modals as $modal) {
// Create modal divs
?>
<div class="modal fade" id='<?php echo $modal['id'] ?>' 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">Weitere Information </h4>
</div>
<div class="modal-body">
<dl class="dl-horizontal">
<dt>Bereich</dt>
<dd><?php echo $modal['Bereich'] ?></dd>
</dl>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div> //<!-- /.modal-content -->
</div>//<!-- /.modal-dialog -->
</div>//<!-- /.modal -->
<?php
}