Hidding A button with JQuery with Conditions - javascript

I have a table called report
and currently im trying to read what is the value in the status column in order to hide or display the retryBtn depending on the value in it.
I have also included the JQuery script by manually copy pasting the code & saving in into a file.
Right now I have wrote a JQuery code that runs on load, but it seems like it wasnt run at all as the log shows nothing. What is the reason that its not running, in the src folder the website is able to detect the JQuery.js script.
Any advice?
Table
<div class="table" id="table_report">
<table class="report" id="report">
<tr>
<th class="column">ID</th>
<th class="column">A</th>
<th class="column">B</th>
<th class="column">Status</th>
<th class="column"> C </th>
<th class="column">D Path</th>
<th class="column"> E</th>
<th class="column">E Path</th>
<th class="column"> F</th>
<th class="column">F Path</th>
<th class="column">G </th>
<th class="column">G Path</th>
<th class="column"> </th>
</tr>
while($row = $statement->fetch(PDO::FETCH_ASSOC)){
$fullPSPath = $G_Path . $row['GPath'];
$fullEPath = $E_Path . $row['EPath'];
$fullDPath = $D_Path . $row['DPath'];
$fullFPath = $F_Path . $row['FPath'];
echo "<tr>"
. "<td>". $row['ID']."</td><td>"
. $row['A']."</td><td>" .$row['B']. "</td><td><span class='status'>". $row['Status'] . "</span></td><td>"
. $row['D']. "</td><td>" . "<a href='download.php?type=D&path=". $fullDPath. "'> $fullDPath</a></td><td>"
. $row['E']. "</td><td>". "<a href='download.php?type=E&path=". $fullEPath. "'> $fullEPath</a></td><td>"
. $row['F']. "</td><td>"
. "<a href='download.php?type=F&path=". $fullFPath. "'> $fullFPath</a></td><td>"
. $row['G']. "</td><td>"
. "<a href='download.php?type=G&path=". $fullGPath . "'> $fullGPath </a></td>"
. "<td><button class='Retry' id='retryBtn'>Retry</button></td>";//button here
echo '</tr>';
}
?>
JQuery
<script type="text/javascript">
'use strict';
$(document).ready(function(){//code not run at all.
$("#report").load(function(){
console.log('here');
var retryBtn = document.getElementById('retry');
//retryBtn.style.visibility = "hidden";
var currentRow = $(this).closest("tr");
var status = currentRow.find(".status");
if(status == "Failed")
{
retryBtn.style.display = "block";
}else{
retryBtn.style.display = "none";
};
});
});
</script>

Related

Select Anchor tag using JavaScript which is dynamically rendered in the DOM using PHP & Fetch API

I'm trying to get the element (anchor tag using class name) using JavaScript which is rendered in the DOM dynamically using PHP and Fetch API. But I'm not able to do this. I've tried many methods but unfortunately not working any methods. But when I do same in jQuery then I can easily get the element by using this...
$(document).on('click', '.delBtn', function(){
});
But the same thing I want to do with JavaScript.
This is my index.php coding
<div class="col-lg-7">
<div class="card">
<div class="card-header lead">All Users</div>
<div class="card-body pre-scrollable" style="max-height: 352px !important;">
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody id="showUsers">
</tbody>
</table>
</div>
</div>
</div>
This is my script.js coding
const showUsers = document.getElementById('showUsers');
async function readData() {
const response = await fetch('action.php?read=1', {
method: 'GET'
});
const data = await response.text();
showUsers.innerHTML = data;
}
readData();
And this is my php coding from where I'm sending the html data
if (isset($_GET['read'])) {
$data = $user->read();
$output = '';
if ($data) {
foreach ($data as $row) {
$output .= '<tr>
<td>' . $row['id'] . '</td>
<td>' . $row['first_name'] . '</td>
<td>' . $row['email'] . '</td>
<td>' . $row['phone'] . '</td>
<td>
Edit
Del
</td>
</tr>';
}
echo $output;
}
}
Now I want the value of id attribute when I click on delete anchor tag using JavaScript.
You can attach the event via addEventListener via its anchor class and get the id attribute
const elems = document.getElementsByClassName('delBtn');
for(let ele of elems) {
ele.addEventListener('click', onDeleteCliked);
}
function onDeleteCliked(event) {
console.log('id', event.target.id);
}
<button class="delBtn" id="1">Delete Button</button>
While adding dynamic event handlers, you just need to add the following line of code as well
document.addEventListener('click',function(e){
if(e.target && e.target.classList.value.indexOf('delBtn') !== -1) {
ele.addEventListener('click', onDeleteCliked);
}
});

ajax or jquery doesn't show data Laravel

I added a search field to show live my data, but nothing works when I fill that field.
I made a route called retour.action, and that's in my controller, so when I try a console.log('test') i can see test in my Console on my browser, but the rest of the code I made doesn't work, and I also get no error
here is my controller
public function action(Request $request)
{
if ($request->ajax()) {
$output = '';
$query = $request->get('query');
if ($query != '') {
$retours = Returnorder::all()
->where('firmaname', 'like', '%' . $query . '%')
->orWhere('ordernumber', 'like', '%' . $query . '%')
->orWhere('status', 'like', '%' . $query . '%')
->get();
} else {
$retours = Returnorder::latest('id')->paginate(15);
}
$total_row = $retours->count();
if ($total_row > 0) {
foreach ($retours as $retour) {
$output .= '
<tr>
<td>' . $retour->firmaname . '</td>
<td>' . $retour->ordernumber . '</td>
<td>' . $retour->status . '</td>
</tr>
';
}
} else {
$output = '<tr>
<td align="center" colspan="5">Geen data gevonden</td>
</tr>
';
}
$retours = array(
'table_data' => $output,
);
echo json_encode($retours);
}
}
And this is my script
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('retour.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(retours)
{
$('tbody').html(retours.table_data);
}
})
}
$(document).on('keypress', '#search', function(){
let query = $(this).val();
fetch_customer_data(query);
});
});
And the HTML is this
#extends('layouts.app')
#section('content')
<div class="container">
<div class="mTop">
<div class="row justify-content-center">
<div class="col-md-10">
#if(session('message'))
<div class="alert alert-success" role="alert">
{{session('message')}}
</div>
#endif
<div class="card">
<div class="card-header">Retourmeldingen</div>
<div class="card-body">
<div class="form-group" >
<label for="search" hidden>Zoeken</label>
<input type="text" name="search" id="search" class="form-control"
placeholder="Typ hier uw zoekopdracht in"/>
</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Firmanaam</th>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col">Ordernummer</th>
<th scope="col">Status</th>
<th scope="col">Verwerkingstijd</th>
<th scope="col">Inzenddatum</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Help me please
I think you first need to be sure that what you're typing is actually being sent back to the router. You can get the value of what you're typing by using this:
$(function() {
$('#search').on('keyup', (e) => {
console.log(e.target.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search" type="text" name="search" />

Refreshing DataTables table populated with loop

I want to update table content without refreshing the page but I fill the table using a loop on the same page. Here is the code I use:
<div id="items_table">
<div class="table-responsive" id="table_allitems">
<table id="products_all" class="table-sm table-bordered table-hover" style="width: 100%;">
<thead class="table-secondary table-hover">
<tr>
<th scope="col">
<center>Код</center>
</th>
<th scope="col">
<center>Име</center>
</th>
<th scope="col">
<center>Баркод</center>
</th>
<th scope="col">
<center>Група</center>
</th>
<th scope="col">
<center>Мярка</center>
</th>
<th scope="col">
<center>Количество</center>
</th>
<th scope="col">
<center>Обект</center>
</th>
<th scope="col">
<center>Доставна цена</center>
</th>
<th scope="col">
<center>Продажна цена</center>
</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="skladove_table">
<?php
$query_checkObekt = "SELECT * FROM obekti WHERE owner='$user_hash'";
$result_checkObekt = mysqli_query($conn, $query_checkObekt);
if(mysqli_num_rows($result_checkObekt) > 0) {
$query = "SELECT * FROM items WHERE owner ='$user_hash'";
$result=mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($result))
{
echo '<tr id="' . $row['unique_id'] . '" onmouseover=showItem(' . $row['unique_id'] . ');>';
echo "<td>" . "<center>" . $row['custom_id'] . "</center>" . "</td>";
echo "<td>" . "<center>" . $row['name'] . "</center>" . "</td>";
echo "<td>" . "<center>" . $row['barcode'] . "</center>" . "</td>";
echo "<td>" . "<center>" . $row['grupa'] . "</center>" . "</td>";
echo "<td>" . "<center>" . $row['quantity_type'] . "</center>" . "</td>";
echo "<td>" . "<center>" . $row['quantity_number'] . "</center>" . "</td>";
echo "<td>" . "<center>" . $row['obekt'] . "</center>" . "</td>";
echo "<td>" . "<center>" . $row['price_delivery'] . "</center>" . "</td>";
echo "<td>" . "<center>" . $row['price_sale'] . "</center>" . "</td>";
echo "<td style='width: 1%; padding-left: 1%; padding-right: 1%;' onclick='deleteItem(" . $row['unique_id'] . ");'><i class='fa fa-close'></i>"."</td>";
echo "</tr>";
}
} else {
//no records found
}
?>
</tbody>
</table>
</div><br
To add new item I use iframe modal and what I want is after closing the modal or just pressing one button table to get refreshed (and if possible to stay on the same page) with the new info without refreshing the page.

no data available in table but data from the database is displayed

The data table displays the the contents of the database but still shows an error message: no data available in table.
how do i fix this, just show the data without the error message
<table name= "displaycase" id="example1" class="table table-bordered table-striped" method = "post">
<thead>
<tr>
<th>Case Title</th>
<th>Court</th>
<th>Dockent Number</th>
<th>Nature</th>
<th>Actions Taken</th>
<th>Status</th>
<th>Due Date </th>
</tr>
</thead>
<tbody>
<tbody class = "searchable">
<?php
if (mysql_num_rows($result) > 0) {
// output data of each row
while ($row = mysql_fetch_assoc($result)) {
echo
"</td><td>" . $row["CaseTitle"] .
"</td><td>" . $row["Court"] .
"</td><td>" . $row["docketNum"] .
"</td><td>" . $row["nature"] .
"</td><td>" . $row["actionsTaken"] .
"</td> <td>" . $row["status"] .
"</td> <td>" . $row["dueDate"] .
"</td></tr>";
}
} else {
}
?>
</tbody>
-
<script>
$( document ).ready(function() {
$("#example1").DataTable({
"paging": false,
"ordering": true,
"info": false,
"language": {
"emptyTable": "No Data"
}
})
});</script>
Remove method = "post" from <table> tag.
Why Two <tbody> tag present inside <table>. Remove One.
Why </td> is closed when it didn't opened yet.
No <tr> opened.
UPDATE CODE:
<table name= "displaycase" id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Case Title</th>
<th>Court</th>
<th>Dockent Number</th>
<th>Nature</th>
<th>Actions Taken</th>
<th>Status</th>
<th>Due Date </th>
</tr>
</thead>
<tbody class = "searchable">
<?php
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
echo
"<tr>".
"<td>" . $row["CaseTitle"] ."</td>".
"<td>" . $row["Court"] ."</td>".
"<td>" . $row["docketNum"] ."</td>".
"<td>" . $row["nature"] ."</td>".
"<td>" . $row["actionsTaken"] ."</td>".
"<td>" . $row["status"] ."</td>".
"<td>" . $row["dueDate"] ."</td>".
"</tr>";
}
} else {
}
?>
</tbody>
</table>
[NOTE: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
That's because you missed a tr and instead you echo </td> in the echo here
while($row = mysql_fetch_assoc($result)) {
echo
"<tr><td>".$row["CaseTitle"].
"</td><td>".$row["Court"].
"</td><td>".$row["docketNum"].
"</td><td>".$row["nature"].
"</td><td>".$row["actionsTaken"].
"</td> <td>".$row["status"].
"</td> <td>".$row["dueDate"].
"</td></tr>";
}

Exclude Specific Columns when exporting data from HTML table to excel

I am using this script for exporting data from HTML table to Excel.
<script>
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
I found this here
but when i export this data it includes all columns in HTML table as expected to do. but my last row contains some icons that i don't want to export to excel.
<div class="row" style="margin-left:20px;">
<div class="grid_4">
<div class="da-panel collapsible">
<input type="button" class="btn btn-success" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel" style="float:right">
<div class="da-panel-content">
<div class="da-panel-title" style="border-top:1px solid #ccc;border-bottom:1px solid #ccc">
<h3 style="padding-left:10px;font-weight:bold;">Staff Training Information</h3></div>
<table class="da-table da-ex-datatable-numberpaging" id="testTable" width="100%">
<thead width="100%">
<tr>
<th width="10%">Staff ID</th>
<th width="10%">Name</th>
<th width="10%">Location</th>
<th width="10%">POCT Test</th>
<th width="10%">Initial Training Date</th>
<th width="10%">Annual Competency Date</th>
<th width="10%">Competency Type</th>
<th width="1%">Next Competency Date</th>
<th width="39%">Action</th>
</tr>
</thead>
<tbody width="100%">
<?php
include_once('database.php');
$pdo = Database::connect();
$sql = 'SELECT * FROM competency';
foreach ($pdo->query($sql) as $row) {
$id = $row['staff_id'];
echo '<tr>';
echo '<td width="10%">'. $row['staff_id'] . '</td>';
$sql1 = "SELECT *FROM staff WHERE StaffID='$id'";
foreach($pdo->query($sql1) as $res)
{
echo '<td width="10%">'. $res['StaffName'] . '</td>';
}
echo '<td width="10%">'. $row['location'] . '</td>';
?>
<td width="10%">
<?php
$s = $row['poct_test'];
$val = explode(" ",$s);
for ($i=0; $i<sizeof($val); $i++)
{
$v = $val[$i];
echo $v."<br/>";
}
?>
</td>
<?php
echo '<td width="10%">'. $row['date_of_initial_training'] . '</td>';
echo '<td width="10%">'. $row['annual_competency'] . '</td>';
echo '<td width="10%">'. $row['type_of_competency'] . '</td>';
echo '<td width="1%">'. $row['next_competency'] . '</td>';
echo '<td width="39%">';
echo '<img src="images/ic_zoom.png" height="16" width="16" />';
echo ' ';
echo '<img src="images/icn_edit.png"/>';
echo ' ';
?>
<img src="images/icn_logout.png"/>
<?php
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
As shown in code that last 3 echo contains update/delete icons. I just want to exclude Action column when exporting the table content in excel.
Any help would be highly appreciated.
You can use selectors from jQuery, clone of your table in memory then remove elements you don't want with appropriate selector.
var $table = $('#testTable').clone();
$table = filterNthColumn($table, 9); //remove Action column
function filterNthColumn($table, n){
return $table.find('td:nth-child('+n+'), th:nth-child('+n+')').remove();
}
make a hidden div under the table
<div class="exportData"> </div>
Then on click of the export button call export.php through ajax and put the result into exportData div. Then you can call your print script on the new data brought.
$.post( "export.php", function( data ) {
$( ".result" ).html( data );
});
Copy past your for loop on export.php and delete the two cols.
I think you can just clone the table firstly, remove the action column, and "tableToExcel" the cloned table.
To make the column removing easier, add class "action_th" to action th, and class "action_td" to action td.
Then it's like this,
var exTable = $('#testTable').clone();
//remove the action th/td
exTable.find('.action_th, .action_td').remove();
//then tableToExcel(exTable, ..
This works for me -
$('#divTableContainer').clone().find('table tr th:nth-child(7),table tr td:nth-child(7)).remove().end().prop('outerHTML')

Categories