i am looking for a help
I have taken a code of adding muliple rows in bootstrap, in which i am trying to get values from select boxes, using php inside a javascript, using ajax it is getting value from a database, it works fine for the first row, but when it comes to the muliple rows, it just get value and again adds to first row, what i need is to get value on same row from where it was picked here is the code
<!DOCTYPE html>
<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">
<meta name="description" content="au theme template">
<meta name="author" content="Hau Nguyen">
<meta name="keywords" content="au theme template">
<!-- Title Page-->
<title>Dashboard 3</title>
<!-- Fontfaces CSS-->
<link href="css/font-face.css" rel="stylesheet" media="all">
<link href="vendor/font-awesome-4.7/css/font-awesome.min.css" rel="stylesheet" media="all">
<link href="vendor/font-awesome-5/css/fontawesome-all.min.css" rel="stylesheet" media="all">
<link href="vendor/mdi-font/css/material-design-iconic-font.min.css" rel="stylesheet" media="all">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- Bootstrap CSS-->
<link href="vendor/bootstrap-4.1/bootstrap.min.css" rel="stylesheet" media="all">
<!-- Vendor CSS-->
<link href="vendor/animsition/animsition.min.css" rel="stylesheet" media="all">
<link href="vendor/bootstrap-progressbar/bootstrap-progressbar-3.3.4.min.css" rel="stylesheet" media="all">
<link href="vendor/wow/animate.css" rel="stylesheet" media="all">
<link href="vendor/css-hamburgers/hamburgers.min.css" rel="stylesheet" media="all">
<link href="vendor/slick/slick.css" rel="stylesheet" media="all">
<link href="vendor/select2/select2.min.css" rel="stylesheet" media="all">
<link href="vendor/perfect-scrollbar/perfect-scrollbar.css" rel="stylesheet" media="all">
<!-- Main CSS-->
<link href="css/theme.css" rel="stylesheet" media="all">
</head>
<?php
$connection = mysqli_connect('localhost','root','','quotation');
?>
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$name1 = count($_POST['name']);
$mail1 = count($_POST['mail']);
$phone1 = count($_POST['phone']);
print_r($name);
echo "<br>";
print_r($mail);
echo "<br>";
print_r($phone);
echo "<br>";
echo $name1;
echo $mail1;
echo $phone1;
}
?>
<br>
<div class="container">
<div class="row">
<div class="col col-sm6">
<a href="#">
<img src="images/icon/Omni_logo_for_web2.png" alt="CoolAdmin" />
<p style="color:gray;"><i>Transforming People and Business</i></p>
</a>
<p>
A-242, Sardar Ali Sabri Rd. <br>
Block-2, Gulshan-e-Iqbal <br>
Karachi. <br>
Phone: 021-3498OMNI(6664) Mobile: 0312-2169325, 0337-7222191
<br> SNTN : S0529023-6
<br>
TaxpayerName : OMNI ACADEMY
</p>
</div>
<div class="col col-sm6">
<h2 style="color:gray">Quotations</h2>
<p>
DATE 2018-12-17
<br>
RFQ# 0308-2018
<br>
Karachi. <br>
Phone: 021-3498OMNI(6664) Mobile: 0312-2169325, 0337-7222191
<br> SNTN : S0529023-6
Customer ID 408
<br>
Customer NTN/SNTN NA
<br>
<br>
Customer Lakson Group
<br>
Valid until: 28-Nov-2018
<br>
Prepared by: FIN-03
</p>
</div>
</div>
</div>
<br>
<form method="post">
<div class="container">
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Name</td>
<td>Gmail</td>
<td>Phone</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
<input type="submit" name = 'submit' value="Subm">
</form>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><select onchange = "myfunc(this.value)" name="name[]" class="form-control" ' + counter + '" ><?php $select_courses = "select * from courses";
$run_select = mysqli_query($connection,$select_courses);
while($row = mysqli_fetch_assoc($run_select)){
$name = $row["name"];
$course_id = $row["course_id"];
?><option value="<?php echo $course_id ?>"><?php echo $name; ?></option> <?php } ?></select></td>';
cols += '<td id="getdata" ' + counter + '"></td>';
cols += '<td><input type="text" class="form-control" name="phone[]' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
function myfunc(datavalue)
{
$.ajax({
url:'getdata.php',
type:'post',
data:{
datapost:datavalue
},
success:function(result){
$('#getdata').html(result);
}
});
}
</script>
<?php include('include/footer.php'); ?>
<!-- end document-->
getdata.php
<?php
$connection = mysqli_connect('localhost','root','','quotation');
?>
<?php
$name_id = $_POST['datapost'];
$q = "select * from courses where course_id = '$name_id'";
$result = mysqli_query($connection,$q);
$rows = mysqli_fetch_assoc($result);
?>
<input type="text" name = "phone[]" value="<?php echo $rows['name']; ?>">
You can do as follows:
Set unique id to your select and getdata.
<select id="select'+counter+'">
<td id="getdata'+counter+'"></td>
You can call change function of select separately or pass id to myfunc and parse it from there.
$(document).on('change', 'select[name="name[]"]', function(){
idName = $(this).attr('id'); //finding id of the element
id = idName.substring(6, idName.length); //finding id number
var datavalue = $(this).val();
myfunc(datavalue, id);
});
Change your myfunc as follows.
function myfunc(datavalue, id) {
$.ajax({
url:'getdata.php',
type:'post',
data:{
datapost:datavalue
},
success:function(result){
$('#getdata'+id).html(result);
}
});
}
And also you need to be careful on maintaining unique ids when deleting rows. You can check here how to dynamically add and remove rows.
Related
How do I edit the design hidden somewhere in this code? Currently this has a functioning search and I want to put an Add button next to a textbox. But I cannot even find the search in this code I'm showing below. I found this datatable template bootstrap on youtube.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Survey Settings</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href=" //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css" rel="stylesheet">
</head>
<body>
<?php
require_once("/dao/CategoryDAO.php");
require_once("/dao/TopicDAO.php");
$category = new CategoryDAO();
$topic = new TopicDAO();
$allCategories_arr = $category->getAllCategories();
$allTopics_arr = $topic->getAllTopicTitles();
?>
<div class="container">
<div class="row">
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<td>Category ID</td>
<td>Category Name</td>
<td >Action</td>
</tr>
</thead>
<tbody>
<?php
foreach($allCategories_arr as $ar) {
echo "<tr>";
echo "<td>" . $ar['category_id'] . "</td>";
echo "<td>" . $ar['categoryname'] . "</td>";
echo "<td><a class='btn btn-default' href='viewsubcategory.php?catid=" . $ar['category_id'] . "' >More Info</a>";
echo "</tr>";
}
?>
</tbody>
</table>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable();
});
</script>
</body>
I discovered that this code was triggering the whole design. Therefore, is there anyway I can show the 'hidden' code in this script? I just want to pud an add button and a textbox next to the search.
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable();
});
</script>
Ok not sure I totally understand your requirements but going from your original post it says an add button by the search box that allows you to insert rows into the datatable. the solution below adds an inline form in the toolbar. then the onclick event adds the row to the datatable.
function category(id, name, action) {
var self = this;
this.id = id;
this.name = name;
this.action = action;
}
function model() {
var self = this;
this.categories = [];
}
var mymodel = new model();
$(document).ready(function() {
mymodel.categories.push(new category('1', 'Cat1', 'Post'));
mymodel.categories.push(new category('2', 'Cat2', 'Get'));
mymodel.categories.push(new category('3', 'Cat3', 'Put'));
var table = $('#mytable').DataTable({
data: mymodel.categories,
columns: [{
data: 'id'
}, {
data: 'name'
}, {
data: 'action'
}
],
dom: '<"toolbar">frtip'
});
$("div.toolbar").html(
'<form class="form-inline">\
<div class="form-group">\
<input type="text" class="form-control" id="rowid" placeholder="id">\
</div>\
<div class="form-group">\
<input type="text" class="form-control" id="name" placeholder="name">\
</div>\
<div class="form-group">\
<input type="text" class="form-control" id="action" placeholder="action">\
</div>\
<input type="button" class="btn btn-danger" id="add" value="add"></input>\
</form>'
);
$('#add').click(function(event) {
table.row.add({
'id': $('#rowid').val(),
'name': $('#name').val(),
'action': $('#action').val()
}).draw(false);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<table class="table table-striped table-bordered" cellspacing="0" width="100%" id="mytable">
<thead>
<tr>
<th>Category Id</th>
<th>Category Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I have a page with a dropdown box at the top populated from the database, when I select an item from the dropdown it gives a list of results with a checkbox at the end of each line, I want to be able to select, using each checkbox, any number of results, and submit a value back into a field in the database for each result selected.
I sort of have this working, but it submits the value to every field in the database, rather than just the ones selected
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="favicon.ico">
<title>Stock Items</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- bootstrap theme -->
<link href="css/bootstrap-theme.css" rel="stylesheet">
<!--external css-->
<!-- font icon -->
<link href="css/elegant-icons-style.css" rel="stylesheet" />
<link href="css/font-awesome.min.css" rel="stylesheet" />
<!-- full calendar css-->
<link href="assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
<link href="assets/fullcalendar/fullcalendar/fullcalendar.css" rel="stylesheet" />
<!-- easy pie chart-->
<link href="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen"/>
<!-- owl carousel -->
<link rel="stylesheet" href="css/owl.carousel.css" type="text/css">
<link href="css/jquery-jvectormap-1.2.2.css" rel="stylesheet">
<!-- Custom styles -->
<link rel="stylesheet" href="css/fullcalendar.css">
<link href="css/widgets.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet" />
<link href="css/xcharts.min.css" rel=" stylesheet">
<link href="css/jquery-ui-1.10.4.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<script src="js/lte-ie7.js"></script>
<![endif]-->
</head>
<body>
<!-- container section start -->
<section id="container" class="">
<?php include("navigation.php"); ?>
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-lightbulb-o"> </i>Stock</h3>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i>Home</li>
<li><i class="fa fa-lightbulb-o"></i>Stock</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
All Stock
</header>
<div class="panel-body">
<form class="form-horizontal" method="post" action="">
<div class="form-group">
<div class="col-lg-8">
<select name="search" class="form-control" required >
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `description` FROM `stock_templates`";
$stock_templates = mysql_query($query);
echo "<option value=''>Select Stock Template</option>";
while ($description=mysql_fetch_assoc($stock_templates)) {
echo "<option value='" . $description['id'] . "'>" . $description['description'] . "</option>";
}
?>
</select>
</div>
<div class="col-lg-1">
<input type="submit" name="filter" value="Search" class="btn btn-success" />
</div>
</div>
</form><br><br>
<?php
if(isset($_POST['formSubmit']))
{
$aDoor = $_POST['check_list'];
if(empty($aDoor))
{
echo("<p>You didn't select any items to add to lease.</p>\n");
}
else
{
$N = count($aDoor);
echo("<p>You selected $N item(s) to add to lease: ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
echo("</p>");
}
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
?>
<?php
ob_start( );
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$query = mysql_query("UPDATE stock SET lease_id = $lease_id");
$result2 = mysql_query($query);
// check if sent
if ($result2) {
?>
<div class="alert alert-success fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Well done!</strong> Your lease items have been successfully saved.
</div>
<?php
} else {
?>
<div class="alert alert-block alert-danger fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Oh snap!</strong> We could not save your lease items.
</div>
<?php
}
}
}
?>
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
// Extract filter information
$count = 0;
$search = mysql_escape_string(#$_POST['search']);
// select data from the database
$query2 = "SELECT * FROM `stock_templates` ORDER BY `stock_templates`.`id` DESC LIMIT 0";
// Perform Logic
if (array_key_exists("filter", $_POST)) {
// query based on search term
$query2 = "SELECT * FROM `stock` WHERE $search=stocktemplate_id AND lease_id=0";
}
$result2 = mysql_query($query2);
// Result
if (mysql_num_rows($result2) < 1) {
echo "<div align='center'><h2>Please select a stock template above and click search</h2></div>";
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" class="form-horizontal" name="check_list[]">
<div class="form-group">
<label class="control-label col-lg-1" for="lease_id">Lease Number *</label>
<div class="col-lg-10">
<select name="lease_id" class="form-control">
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `leasenumber` FROM `lease`";
$leases = mysql_query($query);
echo "<option value=''>Select Lease..........</option>";
while ($lease=mysql_fetch_assoc($leases)) {
echo "<option value='" . $lease['id'] . "'>" . $lease['leasenumber'] . "</option>";
}
?>
</select>
</div>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Item ID</th>
<th>Description</th>
<th>Barcode</th>
<th>Serial</th>
<th>Add To Lease</th>
</tr>
</thead>
<?php
while ($row = mysql_fetch_array($result2))
{
$id = $row["id"];
$lease_id = $row["lease_id"];
$barcode = $row["barcode"];
$serial = $row["serial"];
$stocktemplate_id = $row["stocktemplate_id"];
$qa = 0;
?>
<tbody>
<tr>
<td><?php print $id ?></td>
<td><?php $q = mysql_query("SELECT description FROM stock_templates WHERE id = '$stocktemplate_id'"); while ($row = mysql_fetch_array($q)){$qa = $row["description"];} print $qa ?></td>
<td><?php print $barcode ?></td>
<td><?php print $serial ?></td>
<td><input type="checkbox" name="check_list[]" value="<?php print $id ?>" /></td>
<td></td>
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<input class="btn btn-danger" type="submit" name="formSubmit" value="Add Selected To Lease" />
</div>
</form>
</section>
</div>
</div>
</section>
</section>
<!--main content end-->
</section>
<!-- container section end -->
<!-- javascripts -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="js/jquery.scrollTo.min.js"></script>
<script src="js/jquery.nicescroll.js" type="text/javascript"></script>
<!-- jquery ui -->
<script src="js/jquery-ui-1.9.2.custom.min.js"></script>
<!--custom checkbox & radio-->
<script type="text/javascript" src="js/ga.js"></script>
<!--custom switch-->
<script src="js/bootstrap-switch.js"></script>
<!--custom tagsinput-->
<script src="js/jquery.tagsinput.js"></script>
<!-- colorpicker -->
<!-- bootstrap-wysiwyg -->
<script src="js/jquery.hotkeys.js"></script>
<script src="js/bootstrap-wysiwyg.js"></script>
<script src="js/bootstrap-wysiwyg-custom.js"></script>
<!-- ck editor -->
<script type="text/javascript" src="assets/ckeditor/ckeditor.js"> </script>
<!-- custom form component script for this page-->
<script src="js/form-component.js"></script>
<!-- custome script for all page -->
<script src="js/scripts.js"></script>
</body>
</html>
No worries. Just put the code of insert query inside foreach() loop. Like this:
foreach($_POST['check_list'] as $item)
{
$sql="INSERT/UPDATE Query";
//for example
$sql = "INSERT INTO table_demo (field_1, TARGET_FIELD, field_2, field_3) VALUES (val_1, $item, val_2, val_3)";
$insert = mysqli_query($connection,$sql);
}
//next code of your choice
That is really Easy to give a go.
See this is same as you want.
In this link the first answer by Sean Valsh is your solution.
Giving the array as name of every checkbox will give you only chacked option's id in array while submitted.
https://stackoverflow.com/a/4997271/6834980
Ask if still have the problem. Happy to help.
I am creating a PHP/MySQL based application and it need to be able to carry over session variables into the DataTable plugin I use on a page in my app. The application is rather complicated, so I will explain how it works before I ask specific questions.
On index.php, there is a dropdown menu that shows the departments that use this application within my organization. The department list is generated by a mySQL table that has their department name and department code. The $dept variable stores the department code value from the selected option in the dropdown menu on submit. In turn, the $_SESSION["department"] variable stores $dept and redirects to the checkin page if successful.
<?php
require_once('connection.php');
session_start();
if (isset($_POST['submit']))
{
$dept = $_POST['dept'];
$_SESSION["department"] = $dept;
header("Location: checkin.php");
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
</ul>
</div>
<div class="top-bar-right">
</div>
</div>
<div class="row text-center" style="margin-top: 5%;">
<h1>Syracuse University</h1>
<h2>Visitor Management</h2>
<br/>
<form id="dept" method="post" name="dept">
<?php
echo "<select name='dept'>";
echo '<option>'.'Please select a department'.'</option>';
$query = mysqli_query($VisitorManagement, "SELECT * FROM departments");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['code']."'>".$row['name']
.'</option>';
}
echo '</select>';
?>
<input type="submit" class="button" value="Submit" name="submit">
</form>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The session variable is then carried throughout the site and is used to determine which table needs to be shown. For instance, in checkin.php, we need to display staff members in a dropdown list. We have multiple tables based on the departments using the application. One table we have is called ts_staff If the session variable is stored as the string ts, we do the following steps to make sure the app is connecting to the right database:
We store the session variable from index.php into a global variable on checkin.php $dept = $_SESSION[department];
We create another new variable to concatenate the global variable and the _staff string which is used in all our mySQL staff tables: $staffTable = $dept . "_staff";
Lastly, we use the $staffTable variable as the database table that needs to be displayed: $query = mysqli_query($VisitorManagement, "SELECT * FROM {$staffTable}");
Here's the full checkin.php code:
<?php
// connect to database
require_once('connection.php');
session_start();
//get session variable, if empty, unset and logout
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: index.php");
} else {
$dept = $_SESSION[department];
}
//submit values on submit
if (isset($_POST['submit']))
{
// store form data values
$suid = mysqli_real_escape_string($VisitorManagement, $_POST['suid']);
$staff = mysqli_real_escape_string($VisitorManagement, $_POST['staff']);
$checkinTable = $dept . "_checkin";
// insert varaibles into table rows
$sql = "INSERT INTO {$checkinTable} (suid, staffMember) VALUES ('$suid', '$staff')";
// check if row was inserted correctly
if (mysqli_query($VisitorManagement, $sql)) {
header('Location: thank-you.php');
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($VisitorManagement);
}
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
<li>Check-In</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Admin Login</li>
<li>Logout</li>
</ul>
</div>
</div>
<div class="row text-center" style="margin-top: 5%;">
<h1>Syracuse University</h1>
<!-- replace with whatever department they select -->
<h2>Technical Services</h2>
</div>
<div class="row">
<form id="checkin" method="post" name="checkin">
<div class="row">
<div class="medium-12 columns">
<label>Please Swipe Your SUID Card
<input type="text" placeholder="SUID Number Here" id="suid" name="suid" required>
</label>
</div>
<div class="medium-12 columns">
<label>Who Are You Here to See?
<?php
$staffTable = $dept . "_staff";
echo "<select name='staff'>";
echo '<option value="">'.'Please select a staff member'.'</option>';
$query = mysqli_query($VisitorManagement, "SELECT * FROM {$staffTable}");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['fullName']."'>".$row['fullName']
.'</option>';
}
echo '</select>';
// close connection
mysqli_close($VisitorManagement);
?>
</label>
</div>
<div class="medium-12 columns">
<input type="submit" class="button" value="Submit" name="submit">
</div>
</div>
</form>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The problem is that on reports.php, I am using the DataTables plugin to dynamically organize and filter a table, but I need to be able to carry the session variable over into the plugin so it knows to organize the specific table based on what the user selected on the index.php screen.
reports.php just calls DataTables and using another page, response.php to turn the data from the table into JSON to be displayed. Here's reports.php:
<?php session_start();
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: index.php");
} else {
$dept = $_SESSION[department];
}
$checkinTable = $dept . "_checkin";
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="../css/foundation.min.css" />
<link rel="stylesheet" href="../css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
</head>
<body>
<?php
if (!isset($_SESSION['user'])) {
header("Location: ../login.php"); // If session is not set that redirect to Login Page
}
?>
<div class="top-bar admin">
<div class="top-bar-left">
<ul class="menu">
<li class="menu-text">Visitor Management</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Logout</li>
<li>Help</li>
</ul>
</div>
</div>
<div class="medium-2 columns dash">
<ul>
<li>Dashboard</li>
<li>Staff</li>
<li class="active">Reports</li>
</ul>
</div>
<div class="medium-10 columns">
<div class="row checkin">
<h2>Reports</h2>
<table class="checkin" id="checkin">
<thead>
<tr>
<th>ID</th>
<th>SUID #</th>
<th>Staff Member</th>
<th>Student Name</th>
<th>Student Email</th>
<th>Check In Date/Time</th>
</tr>
</thead>
</table>
<!--<div class="float-left">
Export to Excel
</div>
<div class="float-right">
</div>-->
</div>
</div>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script src="../js/vendor/what-input.min.js"></script>
<script src="../js/foundation.min.js"></script>
<script src="../js/app.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.js"></script>
<script>
$(document).ready(function() {
$('#checkin').DataTable({
"bProcessing": true,
"serverSide": false,
"dom": 'lBfrtip',
"buttons": [
{
extend: 'collection',
text: 'Export',
buttons: [
'copy',
'excel',
'csv',
'pdf',
'print'
]
}
],
"ajax":{
url :"response.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
data: {}
}
});
});
</script>
</body>
</html>
Here's response.php:
<?php
//include connection file
include_once("../connection.php");
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 => 'id',
1 => 'suid',
2 => 'staffMember',
3 => 'studentName',
4 => 'studentEmail',
5 => 'checkinDateTime'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( studentName LIKE '".$params['search']['value']."%' ";
$where .=" OR staffMember LIKE '".$params['search']['value']."%' ";
$where .=" OR studentEmail LIKE '".$params['search']['value']."%' ";
$where .=" OR suid LIKE '".$params['search']['value']."%' ";
$where .=" OR checkinDate LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM `ts_checkin`";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
//$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($VisitorManagement, $sqlTot) or die("database error:". mysqli_error($VisitorManagement));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($VisitorManagement, $sqlRec) or die("error to fetch check-in data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
In response.php, I need to able to replace ts_checkin, which is shown on this line:
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM `ts_checkin`";`
with a variable called $checkinTable that would concatenate similar to how checkin.php does with the staff table. So essentially I would like to have $checkinTable = $dept . "_checkin" with $dept equaling the value of the session variable.
When I go to do this, I get this error from DataTables: DataTables warning: table id=checkin - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
Is it possible to get this working? I would like to keep DataTables as its the best way to achieve on-the-fly table filtering, searching, and sorting (plus it's a highly requested feature by our departments). But I need to be able to set the table based on the session variable.
I apologize for the length of this question. If there needs to be clarification, let me know.
I'm not certain to understand the question...
Are you saying this is not working ?
Did you try it written like this?
(notice the space after FROM. It is necessary!)
$checkinTable = $dept . "_checkin";
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM " . $checkinTable;
For sure, $dept has also to be defined.
And the resulting $checkinTable has to be an existing table name.
Ok...
This looks to be missing in your response.php:
session_start();
$dept = $_SESSION[department];
$checkinTable = $dept . "_checkin";
My application asks the user to select the date from the drop down list. After selecting the date, it will display the list of students who took the exam on that date. The user will then can encode grades then save it. But the saving part is not working.
Here is the code.
$queryselect = mysql_query("SELECT examdateno, examdate from tbl_examdate ORDER BY examdate DESC");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SPORT Qualifying Exam System</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/component.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "encodeinterviewajax.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<body>
<header>
<img src="../images/qes_logob.png" alt="logo">
<button class="hamburger">☰</button>
<button class="cross">˟</button>
</header>
<div class="menu">
<ul>
<a href="encodeinterview.php">
<li>Encode Grades</li>
</a>
<a href="viewinterview.php">
<li>View Grades</li>
</a>
<a href="../index.php">
<li>Logout</li>
</a>
</ul>
</div>
<script>
$(".cross").hide();
$(".menu").hide();
$(".hamburger").click(function () {
$(".menu").slideToggle("slow", function () {
$(".hamburger").hide();
$(".cross").show();
});
});
$(".cross").click(function () {
$(".menu").slideToggle("slow", function () {
$(".cross").hide();
$(".hamburger").show();
});
});
</script>
<div id="content">
<form>
<h1>Exam Dates</>
<select name="examdate" id="examDate" onchange="showUser(this.value)">
<option>Select Exam Date</option>
<?php
while ($row = mysql_fetch_array($queryselect)) {
echo "<option value={$row['examdateno']}>{$row['examdate']}</option>\n";
}
?>
</select>
</form>
</div>
<div id="txtHint">Examinees will be listed here</div>
</body>
</html>
This is the php file
<?php
include '../configuration.php';
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/component.css" />
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/grid.css">
</head>
<body>
<?php
$q = intval($_GET['q']);
$sql = mysql_query("select s.sno, s.fname, s.lname, s.examdate, s.interviewgrade, s.gwa from student s inner join tbl_examdate e on s.examdate=e.examdate where e.examdateno=$q");
?>
<div class="as_wrapper">
<div class="as_grid_container">
<div class="as_gridder" id="as_gridder"></div> <!-- GRID LOADER -->
<form method="post" action="">
<table class="as_gridder_table">
<tr class="grid_header">
<td><div class="grid_heading">Student No.</div></td>
<td><div class="grid_heading">First Name</div></td>
<td><div class="grid_heading">Last Name</div></td>
<td><div class="grid_heading">Exam Date</div></td>
<td><div class="grid_heading">Interview Grade</div></td>
<td><div class="grid_heading">GWA</div></td>
</tr>
<?php
while ($row = mysql_fetch_array($sql)) {
?>
<tr class="<?php
$i+=1;
if ($i % 2 == 0) {
echo 'even';
} else {
echo 'odd';
}
?>">
<td><?php $sno[]=$row['sno'];echo $row['sno']; ?></td>
<td><?php $fname[]=$row['fname']; echo $row['fname']; ?></td>
<td><?php $lname[]=$row['lname'];echo $row['lname']; ?></td>
<td><?php echo $row['examdate']; ?></td>
<td><input type="text" size="3" maxlength="3" name="interview[]"></td>
<td><input type="text" size="3" maxlength="3" name="gwa[]"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="6"><button id="btnUpdate">Save</button>
</tr>
</table>
</form>
<?php
if (isset($_POST['btnUpdate'])){
for($i=0;$i<sizeof($sno);$i++){
$interview = $_POST['interview'][$i];
$gwa = $_POST['gwa'][$i];
$sql1= mysql_query("UPDATE student SET gwa='$gwa', interviewgrade='$interview' where fname='$fname[$i]' AND lname='$lname[$i]' ");
header('Location: encodeinterview.php');
}
}
?>
</div>
</div>
</body>
</html>
I am trying to dynamically load content from my database into a div in my view called dynamic. I have a grid of products to the left of the dynamic div and when a user clicks on one of them I want the dynamic div to be populated with details on the product that they clicked on. Additionally, I would like the page to load with the first product selected and displayed automatically. I have tried to follow several tutorials on how to do this, but all I have done is run in circles. Any help is appreciated. My code is below:
Controller (category.php):
public function product() {
$product_id = $_POST['product_id'];
$data['product'] = $this->Category_model->getOneProduct($product_id);
}
Model (Category_model.php):
public function getOneProduct($id) {
$result = $this->db->query("SELECT *
FROM product
WHERE product_id = ?", array($id));
return $result->row_array();
}
View (category_view.php):
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $page['page_title']; ?></title>
<meta charset="utf-8">
<meta name="keywords" content="<?php echo $page['page_meta_keywords']; ?>"/>
<meta name="description" content="<?php echo $page['page_meta_description']; ?>"/>
<link rel="stylesheet" href="<?php echo base_url(); ?>css/style.css" type="text/css" media="all">
<link rel="stylesheet" href="<?php echo base_url(); ?>css/menu.css" type="text/css" media="all">
<link rel="stylesheet" href="<?php echo base_url(); ?>css/bgstretcher.css" type="text/css" media="all"; />
<link href='http://fonts.googleapis.com/css?family=Didact+Gothic:regular' rel='stylesheet' type='text/css' />
[removed][removed]
[removed][removed]
[removed][removed]
[removed]
$(document).ready(function(){
$('body').bgStretcher({
images: ['<?php echo base_url(); ?>images/background.jpg']
});
$('#slideshowHolder').jqFancyTransitions({
delay: 5000,
width: 483,
height: 573,
});
});
[removed]
</head>
<body>
<div id="main">
<div>/div>
<?php $this->load->view('menu_view'); ?>
<div id="content">
<div id="left">
<div id="slideshowHolder">
<?php foreach ($rotators as $rotator) { ?>
<img src="<?php echo base_url(); ?>images/<?php echo $rotator['rotator_photo']; ?>" width="100%" alt="">
<?php } ?>
</div>
</div>
<div id="right">
<div>
<table width="50%" cellpadding="5" >
<tr>
<?php $sql_endRow = 0;
$sql_columns = 3;
$sql_hloopRow1 = 0;
foreach ($products as $product) {
if($sql_endRow == 0 && $sql_hloopRow1++ != 0) { ?>
<tr>
<?php } ?>
<td align="center">
<a href="">
<img src="<?php echo base_url(); ?>products/<?php echo $product['product_thumbnail']; ?>" />
</a>
</td>
<?php $sql_endRow++;
if($sql_endRow >= $sql_columns) { ?>
</tr>
<?php $sql_endRow = 0;
}
}
if($sql_endRow != 0) {
while ($sql_endRow < $sql_columns) { ?>
<td> </td>
<?php $sql_endRow++;
} ?>
</tr>
<?php }?>
</table>
</div>
<div id="dynamic">
<?php //print_r($one_product); ?>
</div>
</div>
<div>/div>
</div>
</div>
</body>
</html>
</code>
In product(), Make the product_id come from GET instead of POST so that your links will work without javascript.
$product_id = $_GET['product_id'];
In getOneProduct($id):
return json_encode($result->row_array());
HTML:
<table width="50%" cellpadding="5" id="product-grid">
<!-- snip -->
<a href="/your/url/product?product_id=<?php echo $product['product_id']; ?>" data-product-id="<?php echo $product['product_id']; ?>">
<img src="<?php echo base_url(); ?>products/<?php echo $product['product_thumbnail']; ?>" />
</a>
example javascript (jquery):
$('#product-grid a').click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "/your/url/product",
data: "product_id=" + $(this).attr('data-product-id'),
success: function(msg){
var product_data = jQuery.parseJSON(msg);
// do something with product_data
$('#dynamic').html('New product: ' + product_data.product_id);
}
});
});