Generate dropdown lists which will send the selectted item back to server - php

This code allows somebody to pick a class from a drop down menu, in which I convert numbers to alphabet letters. Now I want to send the selected value back to the server:
<table id="example" class="display table" style="width: 100%; cellspacing: 0;">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Hours</th>
<th>Class</th>
<th>Add</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Code</th>
<th>Name</th>
<th>Hours</th>
<th>Class</th>
<th>Add</th>
</tr>
</tfoot>
<tbody>
<?php
$query = "SELECT * FROM class";
$result = mysqli_query($connection,$query) or die ("Couldn’t execute query.");
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>
<td>$row[code]</td>
<td>$row[name]</td>
<td>$row[hours]</td>";
$query1 = "SELECT total FROM classtot where code='$row[code]'";
$result1 = mysqli_query($connection,$query1);
while ($row=mysqli_fetch_assoc($result1))
{
$a=$row['total'];
}
$alphabet = range('A','Z');
$i = 1;
echo "
<td><select id='selectError' data-rel='chosen' name='class'>";
while ($i<=$a)
{
$kls=$alphabet[$i-1];
echo "<option value=$kls> $kls </option>";
$i=$i+1;
}
echo "</select></td>
<td>
<a class='btn btn-primary btn-addon m-b-sm btn-xs' href='home_member.php?page=add&id=$row[code]'>
<i class='fa fa-plus'></i> Add</a>
</td>
</tr>";
}
?>
</tbody>
</table>
How can I pass the slected value from the drop down menu 'class' to the server? I can pass the code, but don't know how to pass the selected class.

To add the chosen class to the URL, you will need to build the URL in JavaScript, because PHP does not know beforehand what the user will choose. Here is your code (only the part that goes through the SQL. In comments I describe several improvements I made (unrelated to your question):
<?php
// Make your query return ALL you need. Avoid second query:
$query = "SELECT class.code, class.name, class.hours, classtot.total
FROM class
INNER JOIN classtot ON classtot.code = class.code";
$result = mysqli_query($connection,$query) or die ("Couldn’t execute query.");
// Keep track of row number, for use in generating unique id property values
$rowIndex = 0;
while($row = mysqli_fetch_assoc($result))
{
$rowIndex++;
echo "<tr>
<td>$row[code]</td>
<td>$row[name]</td>
<td>$row[hours]</td>";
// Just pick the total from the combined query:
$a = $row['total'];
$alphabet = range('A','Z');
// Change id for select: You cannot assign the same id to several elements
echo "
<td><select id='select$rowIndex' data-rel='chosen' name='class' >";
// Use a zero-based for loop instead of a while
for ($i = 0; $i < $a; $i++)
{
// Reference $i now, not $i-1:
$kls = $alphabet[$i];
echo "<option value='$kls'> $kls </option>";
}
// Instead of hard-coding the URL, call a JS function that will make the url
echo "</select></td>
<td>
<a class='btn btn-primary btn-addon m-b-sm btn-xs' href='#'
onclick='gotoClass($rowIndex, \"$row[code]\")'>
<i class='fa fa-plus'></i> Add</a>
</td>
</tr>";
}
?>
</tbody>
</table>
<script>
// The JS function that builds the URL and triggers the navigation to it
function gotoClass(rowIndex, classCode) {
var sel = document.getElementById('select' + rowIndex);
location.href = 'home_member.php?page=add&id=' + classCode
+ '&something=' + sel.value;
return false;
}
</script>
In the above code, you need to change "something" to the correct URL parameter you want to use to pass the selected "alphabet" value.
If you have another select in the table rows, like this:
<select id='select2$rowIndex' data-rel='chosen' name='code' >
then extend the above javascript function as follows:
function gotoClass(rowIndex, classCode) {
var sel = document.getElementById('select' + rowIndex);
var sel2 = document.getElementById('select2' + rowIndex);
location.href = 'home_member.php?page=add&id=' + classCode
+ '&something=' + sel.value
+ '&othervalue=' + sel2.value;
return false;
}

Related

Populating form from table row

I have added a button at the end of the row of my datatable intended to update the information in the database for the specific row chosen.
When I click the update button, a form pops us with the relevant fields to update.
Ideally, I would like the form to be autopopulated with the information from the table row which I have chosen to update
Code...
Table:
<div class="viewalljob tab-pane show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<h2>Edit Job Table</h2>
<table id="edit-job-table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="job_id">ID</th>
<th class="job_date">Date</th>
<th class="job_company">Company Name</th>
<th class="job_contact">Contact</th>
<th class="job_from">From</th>
<th class="job_to">To</th>
<th class="job_driver nowrap">Driver</th>
<th class="job_income">Income (£)</th>
<th class="job_payment">Payment (£)</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!--Fetch from Database-->
<!--Connect To Database-->
<?php
$host_name = 'xxx';
$database = 'xxx';
$user_name = 'xxx';
$password = 'xxx';
$conn = mysqli_connect($host_name, $user_name, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT *,AS markup
FROM `table`
GROUP BY id";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while($result = mysqli_fetch_assoc($query)) {
echo "<tr>
<td class='job_id'>".$result['id']."</td>
<td class='job_date'>".$result['adddate']."</td>
<td class='job_company'>".$result['customer']."</td>
<td class='job_contact'>".$result['addcontact']."</td>
<td class='nowrap job_from'>".$result['addfrom']."</td>
<td class='nowrap job_to'>".$result['addto']."</td>
<td class='nowrap job_driver'>".$result['adddriver']."</td>
<td class='currency job_income'>".$result['addincome']."</td>
<td class='currency job_payment'>".$result['addpayment']."</td>
<td><button type='button' name='update' id=".$result['id']." class='btn btn-warning btn-xs update updatebtn'>Update</button></td>
<td><button type='button' name='delete' id=".$result['id']." class='btn btn-danger btn-xs delete deletebtn'>Delete</button></td>
</tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<div id="contactForm3">
<h1>Edit Job</h1>
<form id="dataForm" name="dataform" method="POST" action="/">
/**** FORM DATA ****/
</form>
</div>
JS to open form:
$(function() {
// contact form animations
$('.update').click(function() {
$('#contactForm3').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm3");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
I have added the update button using <td><button type='button' name='update' id=".$result['id']." class='btn btn-warning btn-xs update updatebtn'>Update</button></td> I have given the id=".$result['id']." hoping that I can use this to populate the form from the ID
I am assuming that I will need to connect to the database table, something like:
<form>
<?php
//Connect to Database ... //
$sql = SELECT * FROM `table`
WHERE ID = ???
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while($result = mysqli_fetch_assoc($query)) {
echo "<span>
<label> label1 </label>
<input value = ".$result['column'].">
</span>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Im hoping that this is correct and someone can help me do this?
Actually you can acheive this using javascript/jquery, get row element from table displayed, from which you can get every columns/inputs value like as below:
$('.updatebtn').on('click', function(e) {
e.preventDefault();
var row = $(this).closest('tr'); //get table row from displayed table.
var form = $('#contactForm3').fimd('form'); //form to be populate.
//make sure your form input field with same name as the column name.
//now create form_data object with key as same name as column/input name .
var form_data = { 'id' : row.find('.job_id').value(),
'adddate' : row.find('.job_date').value(),
.....
'addpayment' : row.find('.job_payment').value()
}
//Apply loop to populate values in form.
$.each(form_data, function(key, value){
form.find('input[name="'+ key +'"]').val(value);
});
});
Then on form submit update database record/row using PHP (hope you know that well, if not let me know I will update my code).

How can i apply the datatable filters to my php code?

I am getting some data and displaying on the table which i have created in my php code however i want to apply the data table filters but i cannot seem to find a solution. I know in html i can assign an id to the table and then call it from a js script using the following code var table = $('#myTable').DataTable({"dom":"ftip"}); however this doesn't seem to work in my code. Perhaps because i am wrapping the html code in php?
Thanks
<script>
$(document).ready(function(){
var table = $('#myTable').DataTable({"dom":"ftip"});
});
</script>
<?php
$conn = mysqli_connect('localhost', 'root', '""', 'calendar');
extract($_POST);
if(isset($_POST['readrecords'])){
$data = '<table class="table table-bordered table-striped" id="myTable">
<tr class="bg-dark text-white">
<th>No.</th>
<th>Title</th>
<th>Driver</th>
<th>Date</th>
</tr>';
$displayquery = "SELECT id,title, driver, start FROM `events` ";
$result = mysqli_query($conn,$displayquery);
if(mysqli_num_rows($result) > 0){
$number = 1;
while ($row = mysqli_fetch_array($result)) {
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['title'].'</td>
<td>'.$row['driver'].'</td>
<td>'.$row['start'].'</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="btn btn-success">Edit</button>
</td>
<td>
<button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
$data .= '</table>';
echo $data;
}
?>
function readRecords(){
var readrecords = "readrecords";
$.ajax({
url:"backend.php",
type:"POST",
data:{readrecords:readrecords},
success:function(data,status){
$('#records_content').html(data);
},
});
}

live search in html table

I want to search by product name then get productdetailsid from db then compare it with each row in this table if it exists , set bachground-color for row!
<div class="input-group m-b"><span class="input-group-btn">
<button type="button" class="btn btn-primary">Go!</button> </span> <input type="text" class="form-control"id="autocomplete">
</div>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th style="text-align: center">#</th>
<th style="text-align: center">Product Name</th>
<th style="text-align: center">Quantity</th>
<th style="text-align: center">Product Price</th>
<th style="text-align: center">Whole Price</th>
<th style="text-align: center">Supplier Name</th>
<th style="text-align: center"></th>
</tr>
</thead>
<tbody>
<?php
$per_page=5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$sql = "select p.productname,p.quantity,p.onesale,p.wholesale,p.productdetailsid,s.fullname from productdetails p , supplier s where s.supplierid = p.supplierID LIMIT $start_from,$per_page";
$count = ($page*5)-4;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<form method=\"post\" action=\"\">";
echo "<tr>";
echo "<td>" . $count++ . "</td>";
echo "<td>" . $row["productname"] . "</td>
<td>" . $row["quantity"] . "</td>
<td>" . $row["onesale"] . "</td>
<td>" . $row["wholesale"] . "</td>
<td>" . $row["fullname"] . "</td>
<td><button type=\"submit\" class=\"btn btn-xs btn-danger\" name=\"removeBtn\"><i class=\"fa fa-times\"></i> </button></td>
<td style=\"display:none;\"><input type=\"hidden\" name=\"id\" value='".$row["productdetailsid"]."'>
</td>"
;
echo "</tr>";
echo "</form>";
}
}
$conn->close();
?>
</tbody>
</table>
</div>
For Live search in the table you need to use AJAX for getting the result, then using that result you can use Javascript loop to find which rows are found and change the color. I would prefer JSON output (JSON array output) from the PHP script, I can use that in Javascript Loop...
in PHP
You need to make a seperate PHP file for getting ajax output...say ajax.php
<?php
//Assuming that 'q' is the POST variable for finding the query
if(!empty($_POST['q']))
{
//Put your database query execution code here with using q as search query
//Set header to JSON
header('Content-Type:application/json');
//assuming that $result is associative array of your SQL query output
which contains array of the rows to be hightlighted
echo json_encode($result);
}
This will give a JSON array output which can be easily read by AJAX or $.post functions...
in Javascript
here's the tricky part. you need to make an ajax call and then use that data to highlight the rows....but first need to give an ID to the table body...
...<tbody id="table1">....</tbody></table>
Then you need to use ajax or $.post function to make the call, I have used $.post as it's simple
/**** Cosidering "input1" is a input element for getting query to be searched with id = input1 ****/
var q_data = $("#input1").val();
$.post(ajax.php,
{
q: q_data
},
function(data,status)
{
$.each($("#table1").find("<tr>"),function(i,value)
{
var element = $(this);
$.each(data,function(i,val2){
if(val2 == $(element).find("<td>").text())
{
$(element).css('background','lgihtyellow');
}
});
});
}
);
The code may not work before suitable changes, but this is the logic and concept of ajax based live search in the table

PHP explode function from checkboxes

I have a form where I'm submitting some values (from checkboxes) to another page and on that page I'm using an explode function to break the string inside the array. But I'm getting an additional (+1) value when I put the count() function on the explode.
HTML
<form name = "view" method = "POST" action ="cart.php">
<table align = 'center' width = '100%' border = '4'>
<tr>
<td colspan = '20' align = 'center'><h2> Viewing all the Products </h2></td>
</tr>
<tr align = 'center'>
<th>Item ID</th>
<th>Name</th>
<th>Price</th>
<th>Select</th>
</tr>
<tr align = 'center' class = "odd">
<?php
while($row = mysql_fetch_array($run))
{
$i_id = $row['item_id'];
$i_name = $row['item_name'];
$i_price = $row['item_price'];
?>
<td><?php echo $i_id; ?></td>
<td><?php echo $i_name; ?></td>
<td><?php echo $i_price; ?></td>
<?php
$item = $i_name ." ". $i_price;
?>
<td><input type="checkbox" name="addcart[]" value="<?php echo $item; ?>" onClick="return KeepCount()" />Tick</td>
</tr>
<?php }?><input type = "hidden" name = "check">
<button type= "submit" onclick = "location.href = 'cart.php';" id = "cart">Add to Cart</button> <?php } ?>
</table>
</form>
PHP (on page 2)
$prd = implode(",",$_POST['addcart']);
$final = explode(",", $prd);
for($i=0; $i<=count($final); $i++)
{
echo count($final); //this is where I'm getting the +1 to original count and hence everything falls apart.
echo $final[$i];
}
Note: I have include all the essential files like config.php and everything in the PHP file already.
Why that much extra code, directly do like below:-
foreach($_POST['addcart'] as $val){
echo $val;
}
Since count() starts counting from 1 and for loop starting from 0.
Replace this line:
for($i=0; $i<=count($final); $i++)
with
for($i=0; $i<=count($final)-1; $i++)

Can each row in an HTML table be numbered?

What I would like to do is number each row in my table. I can't manually number the table myself, as all of the info in it is retrieved from a database. Is this possible with jQuery or PHP? Here's a screen shot of the table:
I tried searching for this, and did not find anything that helped me.
Here is the PHP / HTML that is displaying the table:
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Created on</th>
<th style="width:65px;">Status</th>
<th>Actions</th>
</tr>
<?php
[...]
//Display the results
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
As you can see, it's displayed with a while loop.
If anyone knows a way to number each line in my table with jQuery or PHP, please help me :)
$trCounter=0;
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td>$trCounter++</td>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
or you could always use the :eq api in your jquery selector or its equivalent to work with the index but like I asked it depends on what you want to do with the index.
I would go with PHP solution listed by Atul Gupta.
To add more - you also can to start iteration based on which page you are.
<?php
$i = ($page-1) * $itemsPerPage;
while(....)
{
echo $i;
$i++;
}
?>
if you are on the second page of your list would get something like 11,12,13,14,....
jQuery:
$(function () {
var i = 0;
$('table thead tr').prepend('<th>#</th>');
$('table tbody tr').each(function () {
i += 1;
$(this).prepend('<td>' + i + '</td>');
});
});
PHP
<tr>
<th>Sr. No</th> // Add header for counter
<th>Name</th>
...
</tr>
...
$i=1; // add counter -----------corrected-------------
while($info = mysql_fetch_assoc($result)){
//data
...
echo "
<tr>
<td>$i</td> // include counter to table
<td style=\"min-width: 87px;\">$name</td>
...
</tr>
";
$i++; // increment counter
}
Set an auto increment property in the SQL table, which can be used as an index, and will increase automatically when a new entry is added?

Categories