How to retain in the same selection after refresh? - javascript

How to retain with the same selection in dropdown when refresh or after I submit or delete?
I have this code below that select value from database. I want to back with the same value in select dropdown after I refresh or I submit the form or delete records.
bid.php
<html>
<head>
<script>
function showUser(str) {
var $txtHint = $('#txtHint');
if (str == "") {
$txtHint.html('');
return;
}
$txtHint.load('bid_list.php?q=' + str)
}
</script>
</head>
<body onload=showUser(str="ALL")>
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$result = $mysqli->query("SELECT bid FROM procurement WHERE bid LIKE '13-___' OR bid LIKE '1_-___' OR bid LIKE '2_-___' GROUP BY bid ORDER BY bid");
$option = '';
while($row = $result->fetch_assoc())
{
$option .= '<option value = "'.$row['bid'].'">'.$row['bid'].'</option>';
}
?>
<select name="users" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
<option value="ALL" selected='ALL'>ALL</option>
<?php echo $option; ?>
</select>
<div id="txtHint">
</div>
</body>
</html>
bid_list.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
$q = $_GET["q"];
$where = '';
if ( $q != 'ALL' ) {
$where = " WHERE bid='$q' ";
}
$result1 = $mysqli->query("
SELECT bid, item_name, item_description, unit, unit_cost, quantity, supplier, po_number, po_date, counter, SUM(unit_cost*quantity) AS total_amount
FROM procurement
$where
GROUP BY counter ORDER BY bid
");
echo'<table id="tfhover" cellspacing="0" class="tablesorter" style="text-transform:uppercase;">
<thead>
<tr>
<th colspan="3" id="none" style="cursor: default;"></th>
<th title="Item Name">Item Name</th>
<th title="Item Description">Description</th>
<th title="Example : Pc, Pcs, Box and Etc.">Unit</th>
<th title="Item Price">Unit Cost</th>
<th title="Total Item Quantity">QTY</th>
<th title="Total Price">Total Amount</th>
<th title="Name of Supplier">Supplier</th>
<th title="Purchase Order Date">PO Date</th>
<th title="Purchase Order #">PO #</th>
<th id="none" style="cursor: default;"></th>
</tr>
</thead>';
echo'<tbody>';
while($row = $result1->fetch_assoc()){
if($row['bid'] != '')
{
echo'<tr>
<td align="center"><img src="images/del.png" border="0" width="10" height="10" title="Delete"></td>
<td align="center"><a class="fancybox" href="edit.php?pn='.$row["counter"].'"><img src="images/edit.png" border="0" width="10" height="10" title="Edit"></a></td>
<td align="center"><a class="fancybox" href="comments.php?pn='.$row["counter"].'"><img src="images/remarks.png" border="0" width="10" height="10" title="Remarks and Notes"></a></td>
<td>'.$row['item_name'].'</td>
<td>'.$row['item_description'].'</td>
<td>'.$row['unit'].'</td>
<td>'.number_format($row['unit_cost'], 2, '.', ',').'</td>
<td>'.$row['quantity'].'</td>
<td>'.number_format($row['total_amount'], 2, '.', ',').'</td>
<td>'.$row['supplier'].'</td>
<td>'.$row['po_date'].'</td>
<td>'.$row['po_number'].'</td>
<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="'.$row['counter'].'"></td>
</tr>';
}
}
echo "</tbody></table>";

use a jquery ajax call, and update the DOM when your ajax call succesfully returns. see http://api.jquery.com/jQuery.ajax/

AJAX can be used for interactive communication with a database, please check the web site here : http://www.w3schools.com/php/php_ajax_database.asp
i believe that is what you need.

Related

How do i DELETE a data form my database using output array to call the data and button

I already tried to use href and onclick options to call my deleteAppoint. I can call it, but it won't delete any data in my database, and I don't know how to fix it properly. I've been kind of stuck in this problem for a while now.
Here is the code:
viewAppoint.php
if ($_POST) {
$appoint_id = $_POST["appoint_id"];
$result = "SELECT * FROM appointment WHERE appoint_id='$appoint_id'";
$resultConn = $connect->query($result);
$row = $resultConn->fetch_array();
}
--
<div class="row">
<div class="col-md-12">
<div class="panel panel-success">
<div class="panel-heading">Listing all your Appointments</div>
<div class="panel-body">
<table class="tables" id="manageAppointTable" style="width:100%;">
<thead>
<tr>
<th style="text-align: center;" name="appoint_id"
id="appoint_id">
Appoint ID
</th>
<th style="text-align: center;">Appoint Date</th>
<th style="text-align: center; width: 150px">Item/s</th>
<th style="text-align: center;">Quantity</th>
<th style="text-align: center; width: 100px">Due Date</th>
<th style="text-align: center;">Request Status</th>
<th style="text-align: center;">Maintenance Status</th>
<th style="text-align: center;">Action</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="custom/js/appoint.js"></script>
<?php require_once 'includes/footer.php'; ?>
Here is the code to fetch my data
fetchAppoint.php
require_once 'core.php';
$sql = "SELECT appoint_id, customer_name, customer_contact, order_date,
quantity, due_date, item_type, description, appoint_active, appoint_status,
request_status FROM appointment WHERE appoint_status = 1";
$result = $connect->query($sql);
$output = array('data' => array());
if ($result->num_rows > 0) {
$activeBrand = "";
while ($row = $result->fetch_array()) {
$brandId = $row[0];
$buttons = '<a href="php_action/deleteAppoint.php?delete=true"
class="btn btn-sm btn-danger edit_cat">Delete</a>';
$output['data'][] = array(
$row[0],
$row[3],
$row[6],
$row[4],
$row[5],
$activeCategory,
$activeCategory1,
$buttons
);
}
}
$connect->close();
echo json_encode($output);
Lastly, my code for delete.
deleteAppoint.php
require_once 'core.php';
$valid['success'] = array('success' => false, 'messages' => array());
if ($_POST) {
$appoint_id = $_POST["appoint_id"];
$sql2 = "DELETE from appointment where appoint_id = '$appoint_id'";
if ($connect->query($sql2) === true) {
header('location: http://localhost/inventory-system/viewAppoint.php');
} else {
echo "Failed!";
}
}
Additionally if you decide to get the appoint_id from GET then you must apppend it to href attribute of a tag.

Filtering db table by date

My goals is to make filter for loading posts from 1 week ago, 1 month ago and two inputs from date from and date to ( if one of them is empty to be filled with current date( y-m-d h:m:s ) format
This is all i tried and could have made it to work, every answer is much appreciated, thank you
Tl:dr
Select filter for week ago, month ago
From date - to date ( if one of those is empty then use current date )
Index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$query = "SELECT * FROM tbl_order ORDER BY order_id desc";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Ajax PHP MySQL Date Range Search using jQuery DatePicker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">Ajax PHP MySQL Date Range Search using jQuery DatePicker</h2>
<h3 align="center">Order Data</h3><br />
<div class="col-md-3">
<input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" />
</div>
<div class="col-md-3">
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" />
</div>
<div class="col-md-5">
<input type="button" name="filter" id="filter" value="Filter" class="btn btn-info" />
</div>
<div style="clear:both"></div>
<br />
<div id="order_table">
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["order_id"]; ?></td>
<td><?php echo $row["order_customer_name"]; ?></td>
<td><?php echo $row["order_item"]; ?></td>
<td>$ <?php echo $row["order_value"]; ?></td>
<td><?php echo $row["order_date"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filter.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
And filter.php
<?php
//filter.php
if(isset($_POST["from_date"], $_POST["to_date"]))
{
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
$query = "
SELECT * FROM tbl_order
WHERE order_date BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."'
";
$result = mysqli_query($connect, $query);
$output .= '
<table class="table table-bordered">
<tr>
<th width="5%">ID</th>
<th width="30%">Customer Name</th>
<th width="43%">Item</th>
<th width="10%">Value</th>
<th width="12%">Order Date</th>
</tr>
';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'. $row["order_id"] .'</td>
<td>'. $row["order_customer_name"] .'</td>
<td>'. $row["order_item"] .'</td>
<td>$ '. $row["order_value"] .'</td>
<td>'. $row["order_date"] .'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Order Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
}
?>
Use something like this to make sure that you are getting the correct format from your datepicker:
$("#from_date").datepicker({ dateFormat: 'yy-mm-dd' }).val();
Make PHP variables to use in your query for the date:
$fromDate = !empty($_POST['from_date']) ? "'".mysqli_escape_string($_POST["from_date"])."'" : "CURDATE()";
$toDate = !empty($_POST["to_date"]) ? "'".mysqli_escape_string($_POST["to_date"])."'" : "CURDATE()";
$query =
"SELECT *
FROM tbl_order
WHERE order_date
BETWEEN $fromDate
AND $toDate";
NOTE: You should also add some logic in there to make sure that the from_date does not end up being before the to_date.
NOTE 2: This answer is making the assumption that you have not set up PDO. Always make sure to avoid SQL injection attacks in some way. Any values coming from the front end are unsafe and subject to SQL injection. PDO would be preferable, but escaping will work.
You can try casting your $_POST using CAST function to convert values to date.
$query = "SELECT * FROM tbl_order
WHERE order_date
BETWEEN CAST('".$_POST["from_date"]."' AS DATE)
AND CAST('".$_POST["to_date"]."' AS DATE)";
You can read about it on MySQLTutorial .
Also I recommend you to escape variables when working with database :-) Always expect user is up to no good.

How to Display All Values in Email Body that are Checked Regardless if Visible

I have a multiple column table with one column being checkboxes. If you check a checkbox then press the "Checkout" button, it will take the specified rows and display them in the body of an email.
I originally bring in the top 100 rows to keep the info to a minimum for the user. I also have a search functionality where the user can search for specific rows. The user can maneuver throughout different searches and still keep all of the checkboxes checked with session storage. However, when a user hits "Checkout" the body of the email only displays the table rows that are checked and currently visible on the page.
So, if a user searches for a table row and checks it, but then navigates back to the original top 100 rows by clicking home, that row would not display on the email because it is not displayed in the top 100.
How can I fix this and show ALL rows that have been checked, whether they are visible on the page or not?
JavaScript that sends information to email body:
function sendMail() {
var dataItems = [
{ 'clss':'.loc', 'prop':'loc' },
{ 'clss':'.rp-code', 'prop':'rpCode' },
{ 'clss':'.sku', 'prop':'sku' },
{ 'clss':'.special-id', 'prop':'specialId' },
{ 'clss':'.description', 'prop':'description' },
{ 'clss':'.quantity', 'prop':'quantity' },
{ 'clss':'.unit', 'prop':'unit' }
];
var link = "mailto:me#example.com" + "?subject=" + encodeURIComponent("Order") + "&body=";
link += $('#merchTable tr input[name="check"]:checked').closest('tr').get().map(function(tr) {
var str = dataItems.map(function(item) {
return encodeURIComponent($(tr).find(item.clss).data(item.prop)) + '\xa0\xa0';
}).join('');
str += encodeURIComponent($(tr).find('.spinner').spinner('value')) + '%0D%0A';
return str;
}).join('') + '%0D%0A';
console.log(link);
window.location.href = link;
}
JavaScript that includes code to keep all checkboxes checked throughout session:
$(function(){
var showQuantityHeader = false;
$(':checkbox').each(function() {
// Iterate over the checkboxes and set their "check" values based on the session data
var $el = $(this);
//console.log('element id: ',$el.prop('id'),' sessionStorage[id]: ',sessionStorage[$el.prop('id')]);
$el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
if ($el.prop('checked')) {
//show the quantity cell in the column under header with class num
$el.closest('tr').find('td.quantity_num').toggle(this.checked);
showQuantityHeader = true;
setupSpinner(this);
var quantity = sessionStorage['value_'+$el.prop('id')];
if (quantity) {
$el.closest("tr").find(".spinner" ).spinner( "value", quantity );
}
}
});
if (showQuantityHeader) {
$('#merchTable').find('th.num').show();
//console.log('header with class num: ',$('#merchTable').find('th.num'));
}
$('input:checkbox').on('change', function() {
// save the individual checkbox in the session inside the `change` event,
// using the checkbox "id" attribute
var $el = $(this);
sessionStorage[$el.prop('id')] = $el.is(':checked');
});
});
HTML Table:
<section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>
<br>
<table id="merchTable" cellspacing="5" class="sortable">
<thead>
<tr class="ui-widget-header">
<th class="sorttable_nosort"></th>
<th class="sorttable_nosort">Loc</th>
<th class="merchRow">Report Code</th>
<th class="merchRow">SKU</th>
<th class="merchRow">Special ID</th>
<th class="merchRow">Description</th>
<th class="merchRow">Quantity</th>
<th class="sorttable_nosort">Unit</th>
<th style="display: none;" class="num">Quantity #</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($query) as $row) {?>
<tr>
<td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
<td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
<td class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
<td class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
<td class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
<td class="description ui-widget-content" data-description="<?php echo htmlspecialchars($row['Description']) ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
<td class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
<td class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
<td style="display: none;" class="quantity_num ui-widget-content"><input disabled="true" type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
</tr>
<?php } ?>
</tbody>
</table>

Passing table row element to a js

I have a bootstrap table which element are loaded from a database.
I have a js function to delete a table row from data base, so I add a button in each row of the table.
<table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>client</th>
</tr>
</thead>
<tbody>
<?php
require("config.php");
// Create connection
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_row()) {
$user_id=$row[0];
$user_name=$row[1];
?>
<tr>
<!--here showing results in the table -->
<td><?php echo $user_id; ?></td>
<td ><?php echo $user_name; ?></td>
<td>
<input type="button" class="btn btn-danger btn-xs delete" value="Cancella sin id" onclick="deleteFunction()"/>
</td>
</tr>
</tbody>
</table>
How can I pass to deleteFucntion the id or user_name in order to use them into Javascipt like this:
function deleteFunction() {
var username = #MY_ROW_USERNAME;
....
}
TD's should look like this
<td id="user_name_<?=$user_id?>" onClick="deleteFunction(<?=$user_id?>)"><?=$user_name?></td>
Delete function like this
function deleteFunction(user_id) {
var username = document.getElementById('user_name_'+user_id).innerHTML;
}

how to show data from database in textbox in php

i am new in php programming i have problem in this code, i want to show data in text box when i press select button which is in grid, but i am stuck on it because data not shown in text box and my select button also not working, what i do friends for this,
this is my code
FIRST NAME
MIDDLE NAME
LAST NAME
**--//php code--//**
$qrydatabind='SELECT ecode, first_name, middle_name, last_name, father_name, mother_name,
number_of_dependents, dob, gender, identification_mark, marital_status, spouse_name, mobile_number,
email_id, adhar_id, pan_number, passport_number, tin_number, dl_number FROM USER_MASTER ORDER BY user_id DESC
LIMIT 1';
$results= mysql_query($qrydatabind) or die(mysql_error());
while( $row = mysql_fetch_array( $results ) ) {
echo
"
<div class='table-responsive'>
<table border='1' style= 'background-color: #84ed86; color: #761a9b; ' >
<thead>
<tr>
<th></th>
<th>Entity Code</th>
<th>User Id</th> <th>User Name</th> <th>Father Name</th> <th>Mother Name</th> <th>No.Of Dependents</th>
<th>D.O.B</th> <th>GENDER</th> <th>Id Mark</th> <th>MARITAL STATUS</th> <th>SPOUSE NAME</th>
<th>Mob. Number</th> <th>E-Id</th> <th>ADHAR-ID</th> <th>PAN-No.</th> <th>PASSPORT-No.</th>
<th>TIN-NO.</th> <th>DL-No.</th>
</tr>
</thead>
<tr >
<td><button type='submit' class='btn btn-primary' name='select_button'>Select</button> </td>
<td>{$row['ecode']}</td> <td> echo $row[0];</td>
<td>{$row['first_name']} {$row['middle_name']} {$row['last_name']}</td>
<td>{$row['father_name']}</td> <td>{$row['mother_name']}</td>
<td>{$row['number_of_dependents']}</td> <td>{$row['dob']}</td>
<td>{$row['gender']}</td> <td>{$row['identification_mark']}</td>
<td>{$row['marital_status']}</td> <td>{$row['spouse_name']}</td>
<td>{$row['mobile_number']}</td> <td>{$row['email_id']}</td>
<td>{$row['adhar_id']}</td> <td>{$row['pan_number']}</td>
<td>{$row['passport_number']}</td> <td>{$row['tin_number']}</td>
<td>{$row['dl_number']}</td>
</tr> </table>
</div>";
}}
if(isset($_POST['select_button']))
{
$qrydatabind1='SELECT ecode, first_name, middle_name, last_name, father_name, mother_name,
number_of_dependents, dob, gender, identification_mark, marital_status, spouse_name, mobile_number,
email_id, adhar_id, pan_number, passport_number, tin_number, dl_number FROM USER_MASTER';
$results1= mysql_query($qrydatabind1) or die(mysql_error());
while( $row = mysql_fetch_array( $results1 ) ) {
echo'
<tr >
<td> </td>
<td><input type="text" value="{$row["first_name"]}" ></td>
</tr>';
}
}
It is very simple. as you are putting data in .
Your code
<td> echo $row[0];</td>
Text box code:
<input type="text" value="<?php echo $row[0];?>">
PHP Variables will only be evaluated in strings that are quoted in double quotes "
You should either concatinate a string:
echo '<td><input type="text" value="' . $row["first_name"] . '" ></td>';
Or, use <?php and ?> to switch between script and markup
while( $row = mysql_fetch_array( $results1 ) ) {
?><td><input type="text" value="<?php echo $row["first_name"]; ?>" ></td><?php
}
You can also use this as
echo'<tr><td><input type="text" value="'.$row["first_name"].'" ></td></tr>';

Categories

Resources