I've been trying to do a fast research with Ajax and i want to get a html table inside a xhr.responseText to next get a new research result and i was doing this but i didn't find a way to do it can u please help me resolving it if possible ?
Javascript Function
function changement(str) {
xhr = new XMLHttpRequest();
var input = document.getElementById('rech').value;
xhr.open('GET','?controller=livres&action=search&val=1316', true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("tab").innerHTML = xhr.responseText;
alert(xhr.responseText);
}
};
}
Controller
public function search()
{
if(!isset($_GET['val']))
{
return call('pages','error');
}
$livre= Livre::findByCin($_GET['val']);
//require_once('views/livres/index.php');
}
}
?>
Model Function
public static function findByCin($cin)
{
$db=Db::getInstance();
$cin=intval($cin);
$req=$db->prepare("SELECT * FROM document where ref like '%".$cin."%'");
$req->execute();
$list=[];
foreach ($req->fetchAll() as $temp)
{
$Livre=new Livre();
$Livre->setReference($temp['ref']);
$Livre->setNom($temp['nom']);
$Livre->setDateCreation($temp['date_creation']);
$Livre->setPrix($temp['prix']);
$Livre->setAuteur($temp['auteur']);
$Livre->setnbPages($temp['nbrPages']);
$list[]=$Livre;
}
return $list;
}
HTML page
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">
<strong>Liste des Livres</strong>
</h2>
<hr> <br>
<div class="row">
<div class="col-sm-6">
<a class="pull-left btn btn-default" href="?controller=chercheurs&action=add">
Ajouter Livre</a>
<div class="col-sm-6">
<form action="?controller=livres&action=search" method="POST">
<div class="input-group">
<input type="search" onkeyup="changement(this.value)" name="search" class="form-control" placeholder="Recherche par Réference" id="rech">
<span class="input-group-btn">
<button type="submit" class="btn btn-default" > Filtrer </button>
</span>
</div>
</form>
</div>
</div></div><br>
<div class="table-responsive" id="tab">
<table class="table table-stripped"><thead>
<tr>
<th>Réference</th><th>Nom</th><th>DateCreation</th><th>Prix</th><th>Auteur</th><th>NbrPages</th>
</tr> </thead>
<tbody>
<?php foreach ($livre as $livr) {?>
<tr>
<td><?php echo $livr->getReference(); ?></td>
<td><?php echo $livr->getNom(); ?></td>
<td><?php echo $livr->getDateCreation(); ?></td>
<td><?php echo $livr->getPrix(); ?></td>
<td><?php echo $livr->getAuteur(); ?></td>
<td><?php echo $livr->getnbPages(); ?></td>
<td>
<a class="btn btn-danger" href="?controller=livres&action=delete&id=<?php
echo $livr->getReference(); ?>">
Supprimer </a>
<a class="btn btn-primary" href="?controller=livres&action=edit&id=<?php
echo $livr->getReference(); ?>">
Modifier </a
</td>
</tr> <?php } ?>
</tbody> </table>
</div></div></div></div>
thanks .
Related
Hello guys I want to get the information of previous date or last day only when I press the button and it will display the all information last day (saturday) and if I click the button again it will shows information of last last day (friday) and if I click it again (thursday) thanks for helping me guys
EDITED:
generate_attendance.php
if(isset($_POST['submit1'])){
$prev_date= date('Y/m/d',strtotime("-1 days"));
$query=mysqli_query($dbcon,"select * from attendance where date_added '$prev_date'")or die(mysql_error());
while($row=mysqli_fetch_array($query)){
$attendance_id=$row['attendance_id'];
?>
<tr>
<td><?php echo $row['lastname'].', '.$row['firstname']; ?></td>
<td><?php echo $row['course']; ?></td>
<td><?php echo $row['type']; ?></td>
<td><?php echo $row['year_level']; ?></td> <td><?php echo $row['date_added']; ?</td>
</tr>
<?php
<div class="controls">
<button name="submit1" type="submit1" class="btn btn-success"><i class="icon-plus-sign icon-large"></i> Previous Day</button>
</div>
</div>
generate_attendance.php (full code)
<div class="container">
<div class="margin-top">
<div class="row">
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong><i class="icon-user icon-large"></i> Attendance Report</strong>
</div>
<div class="span12">
<center class="title">
<h1>Attendance List</h1>
</center>
<div class="pull-right">
<i class="icon-print icon-large"></i> Print
</div>
<form method="post">
<div class="span3">
<div class="control-group">
<label class="control-label" for="inputEmail"><!-- Attendance Report --></label>
<div class="controls">
<label class="control-label" for="inputEmail">From</label>
<div class="controls">
<input type="date" name="from_date" id="date1" alt="date" class="IP_calendar" title="d/m/Y">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">To Date</label>
<div class="controls">
<input type="date" name="to_date" id="date2" alt="date" class="IP_calendar" title="d/m/Y">
<!-- <input type="text" class="w8em format-d-m-y highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC;" required/> -->
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="submit" type="submit" class="btn btn-success"><i class="icon-plus-sign icon-large"></i> Search</button>
</div>
</div>
<div class="controls">
<button name="submit1" type="submit1" class="btn btn-success"><i class="icon-minus-sign icon-large"></i> Previous Day</button>
</div>
</div>
<div class="span8">
<div class="alert alert-success"><strong>Attendance Report</strong></div>
<table cellpadding="0" cellspacing="0" border="0" class="table" id="example">
<thead>
<tr>
<th>Name</th>
<th>Program Code</th>
<th>Type</th>
<th>Year level</th>
<th>Date Log-in</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_POST['submit'])){
$from_date=$_POST['from_date'];
$to_date=$_POST['to_date'];
$query=mysqli_query($dbcon,"select * from attendance where date_added between '$from_date' and '$to_date'")or die(mysql_error());
while($row=mysqli_fetch_array($query)){
$attendance_id=$row['attendance_id'];
?>
<tr>
<td><?php echo $row['lastname'].', '.$row['firstname']; ?></td>
<td><?php echo $row['course']; ?></td>
<td><?php echo $row['type']; ?></td>
<td><?php echo $row['year_level']; ?></td>
<td><?php echo $row['date_added']; ?></td>
</tr>
<?php
}}
?>
<?php
if(isset($_POST['submit1'])){
$prev_date= date('Y/m/d',strtotime("-1 days"));
$query=mysqli_query($dbcon,"select * from attendance where date_added between '$curr_date' and '$prev_date'")or die(mysql_error());
while($row=mysqli_fetch_array($query)){
$attendance_id=$row['attendance_id'];
?>
<tr>
<td><?php echo $row['lastname'].', '.$row['firstname']; ?></td>
<td><?php echo $row['course']; ?></td>
<td><?php echo $row['type']; ?></td>
<td><?php echo $row['year_level']; ?></td>
<td><?php echo $row['date_added']; ?></td>
</tr>
<?php
}}
?>
</tbody>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
Probably pass a query parameter, that indicates how many dates it should subtract, so the url looks like this:
yourphpscript.php? days = 3
Then you can get that in the php, and change the date building:
$days = $_GET["days"];
if(!isset($days)){
$days = 1;
}
$days = intval($days);
$prev_date= date('Y/m/d',strtotime("-".$days." days"));
So now the only thing thats missing, is to change the url of the next request, which would look like this:
<form href="?days=<?php echo $days+1;?>" >
You can send the currently displayed date back to the server within the POST-data.
<input type="hidden" name="currently_displayed" value="<?php echo $prev_date ?>">
<button name="submit1" type="submit1" class="btn btn-success"><i class="icon-plus-sign icon-large"></i> Previous Day</button>
Then within your PHP:
if (isset($_POST['currently_displayed'])) {
// Convert as unix-timestamp
$currentlyDisplayed = strtotime($_POST['currently_displayed']);
} else {
// Not posted, assuming user wants to see yesterday (thus $currentlyDisplayed should be today/now)
$currentlyDisplayed = time();
}
// strtotime( $formatString, $relativeTo );
$prev_date= date('Y/m/d',strtotime("-1 days", $currentlyDisplayed));
I would suggest you to use javascript/JQuery AJAX request instead, you can change it instantly and you can KEEP TRACK of how many clicks you did for the number of previous days ! You don't need if isset POST submit1 anymore.
On the button "Submit1" , have an onclick function to AJAX request that sends the value of numberPrevDays. Make sure to KEEP track of this clicks (Heck you can even have another button which is for the next day). There are several ways to do this. Either to just have a global variable that will keep incrementing (or decrementing) BEFORE sending to the AJAX request
Have a seperate file & function php where the it receives the number of Prev days. This file will process the data and output response json your SQL mysqli_fetch_array data
With that output response, just empty and reload the table with the new data
Sorry I didn't write the actual code
So I'm trying to do Ajax POST in my wordpress site which is used in checking if checkboxes are checked and getting their values to get updated on the database on click. Using the usual PHP form submit is the easiest but the fields that I'm trying to get is outside the form.
After button click, I created an alert if the data that I need is being picked up (and they are) so I can continue with the Ajax POST. However, the POST data is not showing when I inserted an alert on the second file.
Here's my code (content-orders.php):
<div class="container">
<div class="row">
<div class="col-sm-6 text-left">
<form class="form-inline" method="post">
<select id="bulk_action_stat" name="bulk_action_stat">
<option value="BA">Bulk Actions</option>
<option value="MTT">Move To Trash</option>
<option value="MP">Mark Processing</option>
<option value="MOH">Mark On-Hold</option>
<option value="MC">Mark Complete</option>
</select>
<button class="btn btn-success" type="submit" id="check-all">Filter</button>
</form>
</div>
<div class="col-sm-6 text-right">
<form class="form-inline" method="get">
<?php $statuses = wc_get_order_statuses(); ?>
<select name="orderstatus" class="custom-select mb-2 mr-sm-2 mb-sm-0">
<option value="any">-- Select Status --</option>
<?php foreach( $statuses as $skey => $status ) : ?>
<option <?php echo ( ( isset( $_GET['orderstatus'] ) && $_GET['orderstatus'] == $skey ) ? 'selected="selected"' : '' )?> value="<?php echo $skey;?>"><?php echo $status;?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Filter" />
</form>
</div>
</div>
<?php
$status_query = 'any';
if(isset( $_GET['orderstatus'] )) {
$status_query = $_GET['orderstatus'];
}
$filters = array(
'post_status' => $status_query,
'post_type' => 'shop_order',
'posts_per_page' => 200,
'paged' => 1,
'orderby' =>'modified',
'order' => 'DESC'
);
$loop = new WP_Query( $filters );
?>
<div class="row">
<div class="table-responsive">
<table class="table responstable table-striped">
<thead>
<tr>
<th><input id="checkAll" type="checkbox"></th>
<th>Order</th>
<th>Purchased</th>
<th>SKU</th>
<th>Ship To</th>
<th>Date</th>
<th>Total</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
if( !($loop->have_posts())) {
?>
<tr>
<td colspan="8" class="text-center">No data.</td>
</tr>
<?php
} else {
while ( $loop->have_posts() ) {
$loop->the_post();
$order = new WC_Order($loop->post->ID);
?>
<tr>
<td><input id="select-item" name="bulk_actions_check" type="checkbox" value="<?php echo $loop->post->ID; ?>"></td>
<td><?php echo $order->billing_first_name." ".$order->billing_last_name; ?></td>
<td>
<?php
foreach ($order->get_items() as $key => $lineItem) {
echo $lineItem['qty']." ".$lineItem['name']."<br />";
}
?>
</td>
<td><?php
foreach ($order->get_items() as $key => $SKUItem) {
$sku_handler = new WC_Product($SKUItem['product_id']);
echo $sku_handler->sku."<br />";
}
?></td>
<td><?php echo $order->get_shipping_address(); ?></td>
<td><?php explode(" ",$order->order_date); echo $order->order_date[0];?></td>
<td><?php echo "$".$order->get_total(); ?></td>
<td><?php echo $order->status; ?></td>
<td>
<form class="form-inline" method="get">
<input type="hidden" name="status_id" value="<?php echo $order->id; ?>" />
<?php if ($order->status != 'cancelled' && $order->status != 'completed') { ?>
<?php if ($order->status != 'processing') { ?>
<button class="btn btn-primary" id="processing-<?php echo $order->id; ?>" type="submit" name="update_status" value="processing"><i class="fa fa-ellipsis-h" aria-hidden="true"></i></button>
<?php }?>
<button class="btn btn-success" id="complete-<?php echo $order->id; ?>" type="submit" name="update_status" value="completed"><i class="fa fa-check" aria-hidden="true"></i></button>
<?php }?>
<button class="btn btn-info" id="view-<?php echo $order->id; ?>" type="submit" name="update_status" value="view"><i class="fa fa-eye" aria-hidden="true"></i></button>
</form>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#checkAll").click(function () {
jQuery('input:checkbox').not(this).prop('checked', this.checked);
});
jQuery('#check-all').click(function(){
var bulk_action_status = jQuery('#bulk_action_stat').val();
var checkValues = jQuery('input[name=bulk_actions_check]:checked').map(function()
{
return jQuery(this).val();
}).get();
alert(checkValues);
jQuery.ajax({
url: '<?php echo get_stylesheet_directory_uri(); ?>/test.php',
type: 'post',
data: { ids: checkValues },
success:function(data){
}
});
});
});
On test.php is just
print_r($_POST);
These 2 files are in my child theme.
I hope someone can help. Thanks!
-Eli
I'm a bellend.
The form should just have an ID and add the form ID to all the fields outside the form.
<form id="bulk_action_filter" class="form-inline" method="post">
<select id="bulk_action_stat" name="bulk_action_stat">
<option value="">Bulk Actions</option>
<option value="trash">Move To Trash</option>
<option value="processing">Mark Processing</option>
<option value="on-hold">Mark On-Hold</option>
<option value="completed">Mark Complete</option>
</select>
<input form="bulk_action_filter" type="submit" name="filter_bulk_actions" id="check-all" value="Apply"/>
</form>
<input form="bulk_action_filter" id="select-item" name="bulk_actions_check[]" type="checkbox" value="<?php echo $loop->post->ID; ?>">
I want to filter Table data, but I have more than hundred row so I used pagination. If i apply any filter it only filters the current page inseated of entier table.
Html and javascript code are given below
<select id='filterText' style='display:inline-block' onchange='filterText()'>
<option disabled selected>Select</option>
<option value='Active'>Active</option>
<option value='Obsolete'>Obsolete</option>
<option value='all'>All</option>
</select>
<table class="table table-striped table-bordered table-hover table-list-search" id="dataTables-example" >
<thead>
<tr style="background-color:#abdcd5;">
<th align="left" class="col-xs-2">Employee ID</th>
<th align="left" class="col-xs-1">Name</th>
<th align="left" class="col-xs-2">Location</th>
<th align="left" class="col-xs-2">Company </th>
<th align="left" class="col-xs-3">Job Description</th>
<th align="left" class="col-xs-1">Status</th>
<th align="left" class="col-xs-1">Action</th>
</tr>
</thead>
<tbody>
<?php employeedetails::employeelist();?>
</tbody>
</table>
Javascript
<script>
function filterText() {
var rex = new RegExp($('#filterText').val());
if(rex == "/all/") {
clearFilter();
} else {
$('.content').hide();
$('.content').filter(function() {
return rex.test($(this).text());
}).show();
}
}
function clearFilter() {
$('.filterText').val('');
$('.content').show();
}
</script>
Php code
<?php
class employeedetails
{
//function for display details of employee
static function employeelist()
{
$tenanPortalId = $_SESSION['PortalID'];
$databaseConnectionObject = new DB_CONNECT();
$resultForGettingDetailsOfEmployees = mysqli_query($databaseConnectionObject->connect(),$Query);
if(!$resultForGettingDetailsOfEmployees){
die(mysqli_error($databaseConnectionObject->connect()));
}
else if($resultForGettingDetailsOfEmployees)
{
while($row = mysqli_fetch_array($resultForGettingDetailsOfEmployees))
{
$employee_ID=$row['employee_id'];
$employee_ID_trim = str_replace($tenanPortalId."~","",$row['employee_id']);
$employee_Name=$row['employee_name'];
$employee_Location=$row['employee_location'];
$employee_Status=$row['employee_Status'];
$expenseManager=$row['expenseManager'];
$SnactionManager=$row['SnactionManager'];
$EmployeeLocation=$row['countryName'];
$hireDate=$row['hireDate'];
if($row['company'] == "->")
{
$company = "";
}
else
{
$company=$row['company'];
}
if($row['reportingLineUnit'] == "->")
{
$reportingLineUnit="";
}
else
{
$reportingLineUnit=$row['reportingLineUnit'];
}
$employeeType = $row['employeeType'];
$jobdescription = $row['jobDescription'];
?>
<tr class="content">
<td>
<a data-toggle="modal" data-target='#<?php echo "$employee_ID_trim"; ?>' style="cursor: pointer;">
<?php echo "$employee_ID";?>
</a>
<?php
$msg = "";
if($SnactionManager == "" || $SnactionManager == "No")
{
$msg = "Do you want to make $employee_Name as Sanction Manager?" ;
}
else
{
$msg = "Do you want to remove $employee_Name as Sanction Manager?" ;
//echo " <span><img src='../assets/img/twouser.png' width='20px;' height='20px;'/></span>";
}
echo $imgPath = ($expenseManager == "Yes") ?
(($SnactionManager == "Yes") ? " <span><img src='../assets/img/twouser.png' width='20px;' height='20px;' title='Project & Sanction Manager'/></span>" : " <span><img src='../assets/img/project.png' width='20px;' height='20px;' title='Project Manager'/></span>" )
:
(($SnactionManager == "Yes") ? " <span><img src='../assets/img/sanction.png' width='20px;' height='20px;' title='Sanction Manager'/></span>" : "" ) ;
?>
<!-- Modal -->
<div id='<?php echo "$employee_ID_trim"; ?>' class="modal fade" role="dialog" ">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">
<?php echo "$employee_Name";?>
</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<tr style="background-color:#abdcd5;">
<th align="left" class="col-xs-2">Project Manager</th>
<th align="left" class="col-xs-2">Sanction Manager</th>
<th align="left" class="col-xs-2">Type</th>
<th align="left" class="col-xs-2">Reporting Line Unit </th>
<th align="left" class="col-xs-2">Hire Date </th>
</tr>
<tr>
<td><?php echo "$expenseManager";?></td>
<td><?php echo "$SnactionManager";?></td>
<td><?php echo "$employeeType";?></td>
<td><?php echo "$reportingLineUnit";?></td>
<td><?php echo date("m/d/Y", strtotime($hireDate));?></td>
</tr>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</td>
<td>
<?php echo "$employee_Name"; ?>
</td>
<td><?php echo "$EmployeeLocation";?></td>
<td><?php echo "$company";?></td>
<td><?php echo "$jobdescription";?></td>
<?php $color =($employee_Status=="Obsolete" ? "red" : "green") ; ?>
<td style="color:<?php echo $color; ?> ;font-weight:bold;text-align:center;"><?php echo "$employee_Status";?></td>
<td align="center">
<button type="button" style="background-color:#00a4a4;border-color:#00a4a4;" class="btn btn-primary btn-xs" data-toggle="modal" data-target='#<?php echo "$employee_ID_trim"."SMM"; ?>' style="cursor: pointer;">
<span class="glyphicon glyphicon-pencil"></span>
</button>
<div id='<?php echo "$employee_ID_trim"."SMM"; ?>' class="modal fade" role="dialog" ">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">
<?php echo "$employee_Name";?>
</h4>
</div>
<div class="modal-body">
<div class="row" style="padding-bottom:5%;">
<?php echo $msg; ?>
</div>
<div class="row" style="padding-bottom:3%;">
<form id="eventForm" action="../index.php" method ="POST">
<input type="hidden" class="form-control" id="" name="EmployeeId" value="<?php echo "$employee_ID"; ?>" />
<input type="hidden" class="form-control" id="" name="EmployeeName" value="<?php echo "$employee_Name"; ?>" />
<?php
$buttonName = "Assign";
if($SnactionManager == "" || $SnactionManager == "No")
{
?>
<input type="hidden" name="SnManager" value="Yes">
<?php
}
else
{
$buttonName = "Remove";
?>
<input type="hidden" name="SnManager" value="No">
<?php
}
?>
<button type="submit" class="btn btn-primary" value="Assign Manger" name="operation">
<span class="glyphicon glyphicon-ok" ></span>
<?php echo $buttonName; ?>
</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">
<span class="glyphicon glyphicon-remove" ></span>
Cancel
</button>
</form>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
<?php
} //while
} //else if
} //function
} //class
?>
I want to display search result on click of button, but my code is giving me the search result without click on button.
I think it's giving me the query result not the search result.
This code is working fine when I display the result on the page, but as per my requirement I want to display the search result on a popup.
I have used jquery popup.
<body><form action="#" method="POST"><body><form action="#" method="POST"><div data-role="page">
<div data-role="main" class="ui-content" >
Smart Search
</div>
<div data-role="popup" id="a" class="col-sm-6 ui-content">
<div class="input-group col-sm-8">
<input type="text" name="query" class="form-control" placeholder="Search Products to Buy..." " />
<span class="input-group-btn">
<button name ="search_btn" id ="search class="btn btn-warning" type="submit" value="Search" style="background-color:orange;">Search</button>
</span>
</div><div class="input-group col-sm-8 " ><table class="table table-hover">
<thead >
<tr bgcolor="#1E90FF">
<th>Products</th>
<th>Details</th>
<th>Retailers</th>
<th>Price</th>
<th>Buy</th>
</tr>
</thead>
</div><?php
error_reporting(0);
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("wordpress") or die(mysql_error());
?><?php $query = $_POST['query']; $query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw_results=mysql_query("select feed_product_image,feed_product_name,price,deeplink,image from wp_pc_products_merchants e,wp_pc_products w where e.slug=w.id_merchant and feed_product_name LIKE '%".$query."%'") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0)
{
while($results = mysql_fetch_array($raw_results))
{ ?><div class="input-group col-sm-8" style="text-align:center;margin-top:10px;"><tbody>
<tr>
<td><img src = "<?php echo $results['feed_product_image']; ?>" style="object-fit:contain;height:70px;width:100px;" /></td>
<td><?php echo "<p>".$results['feed_product_name']. "</p>" ; ?></td>
<td><img src = "<?php echo $results['image']; ?>" style="background-size:contain;height:40px;width:120px;" /></td>
<td><?php echo '<i class="fa fa-inr"> '.$results['price']. '</i>'.".00" ; ?></td>
<td>Buy now</td>
</tr>
</tbody>
</div>
<?php
}
}
else
{ // if there is no matching rows do following
echo "No results";
}
?>
</div>
</form>
</div>
This will give you search results in modal popup. I have changed your code around a bit. You can popup in case of no search results too.
<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 src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="main" class="ui-content" >
Smart Search
</div>
<div data-role="popup" id="a" class="col-sm-6 ui-content">
<div class="input-group col-sm-8">
<form method="POST">
<input type="text" name="query" class="form-control" placeholder="Search Products to Buy..." " />
<span class="input-group-btn">
<button name ="search_btn" id ="search" class="btn btn-warning" type="submit" value="Search" style="background-color:orange;">Search</button>
</span>
</form>
</div>
<?php
if(isset($_POST['query']) && $_POST['query']!="" ) {
error_reporting(0);
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("wordpress") or die(mysql_error());
$query = $_POST['query']; $query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw_results=mysql_query("select feed_product_image,feed_product_name,price,deeplink,image from wp_pc_products_merchants e,wp_pc_products w where e.slug=w.id_merchant and feed_product_name LIKE '%".$query."%'") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0)
{
?>
<div class="input-group col-sm-8 modal-box" id="popup" title="Search Results" style="text-align:center;margin-top:10px;">
<table class="table table-hover">
<thead >
<tr bgcolor="#1E90FF">
<th>Products</th>
<th>Details</th>
<th>Retailers</th>
<th>Price</th>
<th>Buy</th>
</tr>
</thead>
<tbody>
<?php
while($results = mysql_fetch_array($raw_results))
{ ?>
<tr>
<td><img src = "<?php echo $results['feed_product_image']; ?>" style="object-fit:contain;height:70px;width:100px;" /></td>
<td><?php echo "<p>".$results['feed_product_name']. "</p>" ; ?></td>
<td><img src = "<?php echo $results['image']; ?>" style="background-size:contain;height:40px;width:120px;" /></td>
<td><?php echo '<i class="fa fa-inr"> '.$results['price']. '</i>'.".00" ; ?></td>
<td>Buy now</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php
}
else
{ // if there is no matching rows do following
echo "No results";
}
}
?>
</div>
</form>
</div>
<script>
$(function() {
$( "#popup" ).dialog();
});
</script>
I have a datatable that is displaying 6 total columns of data from my database. The 7th column is a "+" button that expands down and displays a further 7 pieces of data about that specific entry. I am also using Codeigniter for my framework. Originally I was using colspan to make the row hidden and squeeze down, and found out that was a no-no, so I looked into Datatables child rows here: https://datatables.net/examples/api/row_details.html but it appears that the data needs to be there after the generation of the table.
I have the HTML/PHP to generate the table and populate it with data now. The data is sent from my model to controller and to this view:
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover" id="dataTables-listlg">
<thead>
<th>ItemID</th>
<th>Name</th>
<th>Quantity</th>
<th>Identified?</th>
<th>Item Type</th>
<th>Unique ID</th>
<th>Details</th>
</thead>
<tbody>
<?php foreach ($storage_items as $storageItem) { ?>
<tr>
<td><?php echo $storageItem['nameid']; ?></td>
<td><?php echo $storageItem['name']; ?></td>
<td><?php echo $storageItem['amount']; ?></td>
<td><?php echo $storageItem['identify']; ?></td>
<td><?php echo $item_types[$storageItem['type']]; ?></td>
<td><?php echo $storageItem['unique_id']; ?></td>
<td><center><a data-toggle="collapse" data-parent="#accordion" href="#storagedetails<?php echo $storageItem['id']; ?>"><button type="button" class="btn btn-primary btn-circle btn-sm"><i class="fa fa-plus"></i></button></a></center></td>
<td>
<?php echo form_open('/account/edititem', array('class' => 'form-inline'), array('id' => $storageItem['id'], 'item_loc' => "inventory", 'acctid' => $acct_data->account_id)); ?>
</td>
</tr>
<tr>
<td colspan="8" class="hiddenRow">
<div id="storagedetails<?php echo $storageItem['id']; ?>" class="panel-collapse collapse">
<div class="panel-body">
<div class="row">
<div class="col-xs-2">
<strong>Refine level:</strong> <input type="number" name="refine" class="form-control" value="<?php echo $storageItem['refine']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> />
</div>
<div class="col-xs-2">
<strong>Broken?:</strong> <input type="checkbox" name="attribute" class="form-control" value="1" <?php if ($storageItem['attribute'] == 1) { echo "checked"; } if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "disabled"; } ?> />
</div>
<div class="col-xs-2">
<strong>Bound?:</strong> <input type="checkbox" name="bound" class="form-control" value="1" <?php if ($storageItem['bound'] == 1) { echo "checked"; } ?> />
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<strong>Card 1:</strong> <input type="number" name="card0" class="form-control" value="<?php echo $storageItem['card0']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 2:</strong> <input type="number" name="card1" class="form-control" value="<?php echo $storageItem['card1']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 3:</strong> <input type="number" name="card2" class="form-control" value="<?php echo $storageItem['card2']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 4:</strong> <input type="number" name="card3" class="form-control" value="<?php echo $storageItem['card3']; ?>" <?php if ($storageItem['type'] != 4 && $storageItem['type'] != 5) { echo "readonly"; } ?> /></br>
</div>
</div>
<?php echo form_close(); ?>
</div>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
The javascript I'm using now to make the table is:
<script>
$(document).ready(function() {
$('#dataTables-listlg').DataTable({
"responsive": true,
"lengthMenu": [ [25, 50, 100, -1], [25, 50, 100, "All"] ],
"searching": false,
"defaultContent": "",
});
});
</script>
Where the <td colspan="8" class="hiddenRow"> is, is where I want to make the child row drop down (UNDER the entry showing the additional information). I've seen the example but I have no idea how to get my data into the proper format to put it into the datatable and where it should go. Here is the controller with the relevant part:
$data['storage_items'] = $this->accountmodel->get_storage_items($aid);
$this->load->view('account/details',$data);
$this->load->view('footer'); // Where the javascript is above
And the model:
function get_storage_items($aid) {
$this->db->select('*');
$this->db->from('storage')->order_by('storage.id', 'asc');
$this->db->where('storage.account_id', $aid); // This is just sorting out the results from that specific account
$q = $this->db->get();
return $q->result_array();
}
It looks like I need to get my array of results from my model into json/ajax but have no idea how I'd get this all the way to my footer AFTER the table is generated. Any help you can provide would be appreciated.
---Edit---
After looking over the answer below and mulling over thoughts, I have changed things to the following. Here is the complete view from foreach loop to the end, including the Javascript to put stuff in the 'content' array:
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover display" id="dataTables-listlg">
<thead>
<th>ItemID</th>
<th>Name</th>
<th>Quantity</th>
<th>Identified?</th>
<th>Item Type</th>
<th>Unique ID</th>
<th>Details</th>
<th>Options</th>
</thead>
<tbody>
<?php foreach ($storage_items as $storageItem) { ?>
<tr>
<td><?php echo $storageItem['nameid']; ?></td>
<td><?php echo $storageItem['name']; ?></td>
<td><?php echo $storageItem['amount']; ?></td>
<td><?php echo $storageItem['identify']; ?></td>
<td><?php echo $item_types[$storageItem['type']]; ?></td>
<td><?php echo $storageItem['unique_id']; ?></td>
<td class="details-control"></td>
<td>
<button type="submit" class="btn btn-success btn-sm <?php if ($check_perm['editstorageitem'] == 0) { echo "disabled"; } ?>" >Edit</button>
<button type="button" class="btn btn-danger btn-sm <?php if ($check_perm['editstorageitem'] == 0) { echo "disabled"; } ?>">Delete</button>
</td>
</tr>
<script>
var content = [];
content[<?php echo $storageItem["id"]; ?>] = '"'<?php echo form_open("/account/edititem", array("class" => "form-inline"), array("id" => $storageItem["id"], "item_loc" => "inventory", "acctid" => $acct_data->account_id)); ?> \
<div class="panel-body"> \
<div class="row"> \
<div class="col-xs-2"> \
<strong>Refine level:</strong> <input type="number" name="refine" class="form-control" value="<?php echo $storageItem["refine"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /> \
</div> \
<div class="col-xs-2"> \
<strong>Broken?:</strong> <input type="checkbox" name="attribute" class="form-control" value="1" <?php if ($storageItem["attribute"] == 1) { echo "checked"; } if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "disabled"; } ?> /> \
</div> \
<div class="col-xs-2"> \
<strong>Bound?:</strong> <input type="checkbox" name="bound" class="form-control" value="1" <?php if ($storageItem["bound"] == 1) { echo "checked"; } ?> /> \
</div> \
</div> \
<br /> \
<div class="row"> \
<div class="col-xs-2"> \
<strong>Card 1:</strong> <input type="number" name="card0" class="form-control" value="<?php echo $storageItem["card0"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br> \
</div> \
<div class="col-xs-2"> \
<strong>Card 2:</strong> <input type="number" name="card1" class="form-control" value="<?php echo $storageItem["card1"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br> \
</div> \
<div class="col-xs-2"> \
<strong>Card 3:</strong> <input type="number" name="card2" class="form-control" value="<?php echo $storageItem["card2"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br> \
</div> \
<div class="col-xs-2"> \
'<strong>Card 4:</strong> <input type="number" name="card3" class="form-control" value="<?php echo $storageItem["card3"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br> \
</div> \
</div> \
<?php echo form_close(); ?> \
</div>'"';
</script>
<tr item_id="<?php echo $storageItem['id']; ?>">
</tr>
<?php } ?>
</tbody>
</table>
</div>
and my javascript in the footer looks like this now:
<script>
$(document).ready(function() {
var table = $('#dataTables-listlg').DataTable({
"responsive": true,
"lengthMenu": [ [25, 50, 100, -1], [25, 50, 100, "All"] ],
"searching": false,
"defaultContent": "",
});
// Add event listener for opening and closing details
$('#dataTables-listlg tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(content[tr.attr('item_id')]).show();
tr.addClass('shown');
}
});
});
</script>
In fact, the 'unique_id' in this table is not as "unique" as I thought (I didn't design it, just writing the backend for it). There is however a unique key on the table 'id', so that's what I'm using to make sure I get the right value.
This however is not working. I am getting an error in the console:
SyntaxError: missing ; before statement - appears on the line that starts content[<?php echo $storageItem["id"]; ?>] =... in each iteration of the foreach
I'm also getting the error from the webpage warning about DataTables: DataTables warning: table id=dataTables-listlg - Requested unknown parameter '0' for row 1. For more information about this error, please see http://datatables.net/tn/4
Additionally, the child row doesn't drop down. Did I misunderstand or make a silly mistake?
dataTables child rows dynamically injects a row on the form
<tr colspan="number of columns">
<td>
... user content ...
</td>
</tr>
user content is passed to the injected row upon the call (from the example) :
row.child(<user content>).show();
You cannot use hidden rows as a base for child rows. I would suggest you collect all the content you output to hidden rows in the loop into a javascript array :
var content = [];
content[<? echo $storageItem['unique_id']; ?>] = '"'+<? echo form_open(...) + everything from your .hiddenRow. Now follow the example, populate each <tr> with the unique_id
<tr uniqueId="<? echo $storageItem['unique_id']; ?>">
dedicate one column to activate the child row by adding a .details-control and instead of calling the function format() as in the example, do a
row.child(content[tr.attr('uniqueId')]).show();
Update. Jguy, what about
1) fist make your code to work only by inserting simple content. For example row.child('hello').show(); By that you will know that part is working.
2) Then, build up the content array separetely. You do not have to do it all in the same foreach(). This may improve the chance of success if you split the things up in "logical" operations.
3) remember to set an item_id on the <tr>'s
4) your dataTables version cannot be outdated in this context as long as you are using 1.10.x