all data is in page 1 after calling tbody via AJAX - javascript

May I ask for assistance regarding this matter? I checked every guide regarding this concern, and followed all guide, but no luck.
When the table is populated via AJAX call, all the data is in a single page only.
I tried adding the whole dataTable script into the tbody caller, but no luck.
These are the following codes.
This is my <?php include 'ajax-process/earnings_amendment_account-ajax-table.php'; ?>
<script>
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url:'table_body/earnings_amendment_account_table_body.php',
dataType:'json',
type:'get',
cache:true,
success:json,
});
function json(data){
$("#earnings_amendment_account_body").empty();
$(data).each(function(index,value) {
console.log(value);
var table = '<tr>' +
'<td>' + value.accountcode + '</td>'+
'<td>' + value.accounttitle + '</td>'+
'<td>' + value.accounttype + '</td>'+
'</tr>';
$('#earnings_amendment_account').append( table );});
}
}, 1000);
$('#earnings_amendment_account').dataTable();
});
</script>
This is my table in index.php
<table id="earnings_amendment_account" class="table table-bordered" style="table-layout: fixed; display: none">
<thead>
<th>Account Code</th>
<th>Account Title</th>
<th>Account Type</th>
</thead>
<tbody id="earnings_amendment_account_body">
</tbody>
</table>
This is my table_body/earnings_amendment_account_table_body.php
<?php
include '../backend/conn.php';
include '../backend/session.php';
$params=array();
$sql = "SELECT accountcode,accounttype,accounttitle,accounttype,postedby,dateposted,
approvedby,dateapproved FROM earningsamendmentaccount";
$query = sqlsrv_query($conn, $sql, $params, array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if ($query === false ) { echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true); exit; }
$dbdata = array();
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
$dbdata[]=$row;
}
echo json_encode($dbdata);
?>
This is my dataTable.
// all of the function in this dataTable is still not included because I'm testing if everything works well when my dataTable body is being called via AJAX.
<script>
function format ( dataSource ) {
var html = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;" class="table table-bordered">';
for (var key in dataSource){
html += '<tr>'+
'<td>' + key +'</td>'+
'<td>' + dataSource[key] +'</td>'+
'</tr>';
} return html += '</table>'; }
var earnings_amendment_account_table = $('#earnings_amendment_account').DataTable({
"pagingType": "full_numbers"
});
$('#earnings_amendment_account').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = earnings_amendment_account_table.row(tr);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
row.child(format({
'Posted By : ' : tr.data('key-1'),
'Date Posted : ' : tr.data('key-2'),
'Approved By : ' : tr.data('key-3'),
'Date Approved : ' : tr.data('key-4')
})).show();
tr.addClass('shown');
} });
</script>
The data is being passed on console. Showing 0 out of 0 Entries, but the data is on display in the page.
Top:
Bottom:
Thank you so much in advance.

here is i did basic example of datatabe, you need to follow this things if you are using datatable and do custom thing.
Index.php
<!DOCTYPE html>
<html leng="en">
<head>
<title>Display Emloyee </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="table-responsive">
<table class="table table-striped" id="tabl_user">
<thead>
<tr>
<th>Id</th>
<th>F Name</th>
<th>L Name</th>
<th>Gender</th>
</tr>
</thead>
</table>
</div>
<script>
$(document).ready(function()
{
$('#tabl_user').DataTable( {
"processing": true,
"serverSide": true,
"lengthMenu": [5, 10, 25, 50, 100, 150],
"columnDefs" : [{orderable:false, targets:[1] }],
"ajax": "trylimited.php"
} );
});
</script>
</div>
</div>
</body>
</html>
trylimited.php
<?php
include "con.php";
$column = array('id', 'first_name', 'last_name', 'phone_no', 'mobile','city', 'zip');
$sIndexColumn = "id";
$sTable = "elision_user";
// Searching
$wherecondition = "";
if($_REQUEST['search']['value'] != "")
{
$wherecondition = "WHERE (";
for($i=0; $i<count($column); $i++)
{
$wherecondition .="".$column[$i]." LIKE '%".$_REQUEST['search']['value']."%' OR ";
}
$wherecondition = substr_replace($wherecondition, "", -3);
$wherecondition .=')';
}
$draw = $_REQUEST['draw'];
$start = $_REQUEST['start'];
$limit = $_REQUEST['length'];
$sql = "SELECT * FROM allinone";
$res = mysqli_query($con, $sql);
$sql1 = "SELECT * FROM elision_user";
$sql1.=" $wherecondition ORDER BY ".$column[$_REQUEST['order'][0]['column']]." ".$_REQUEST['order'][0]['dir']." limit $start, $limit";
$res1 = mysqli_query($con, $sql1);
$recordsTotal = mysqli_num_rows($res1);
$recordsFiltered = mysqli_num_rows($res);
$asd = array();
$final_array = array();
while( $row = mysqli_fetch_array($res1) ) {
$dataArray = array();
$dataArray[] = $row["id"];
$dataArray[] = $row["first_name"];
$dataArray[] = $row["last_name"];
$dataArray[] = $row["phone_no"];
$dataArray[] = $row["mobile"];
$dataArray[] = $row["city"];
$dataArray[] = $row["zip"];
$asd[]=$dataArray;
}
$final_array = array("draw" => $draw, "recordsTotal" => $recordsTotal, "recordsFiltered" => $recordsFiltered, "data" => $asd, "sql" => $sql1);
echo json_encode($final_array); exit;
?>
Hope this example will help you for your concern.
please vote positive if this example will helpfull

Related

Datatables external link and money currency problem

Im trying to add external link to "customer_id" link example has to be like this /edit-customer.php?customer_id=$customer_id(which is link to original customer id) I am creating big detail page most informations its not in the table
I want to add '$' and money format has to be $ 1,250.00. this my code
<script>
$(document).ready(function() {
var dataTable = $('#customer_table').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "serverside/ajax-users.php",
type: "POST"
}
});
$('#customer_table').on('draw.dt', function() {
$('#customer_table').Tabledit({
url: 'serverside/action.php',
dataType: 'json',
columns: {
identifier: [0, 'customer_id'],
editable: [
[1, 'customer_store', '{"1":"B2C","2":"B2B"}'],
[2, 'customer_name'],
[3, 'customer_address'],
[4, 'customer_phone'],
[5, 'customer_email'],
[6, 'customer_status', '{"1":"Inactive","2":"Active"}']
]
},
restoreButton: false,
onSuccess: function(data, textStatus, jqXHR) {
if (data.action == 'delete') {
$('#' + data.customer_id).remove();
$('#customer_table').DataTable().ajax.reload();
}
}
});
});
}); <
/script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<table id="customer_table" class="display nowrap form-inline" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Store ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
<th>Status</th>
<th>Signing Date</th>
<th>Orders</th>
<th>Total Sales</th>
<th>Detail</th>
</tr>
</thead>
<tbody></tbody>
</table>
//AJAX-USER.PHP
<?php
link db
$column = array("customer_id", "customer_store", "customer_name", "customer_address", "customer_phone", "customer_email", "customer_status", "customer_date", "customer_order", "customer_sale");
$query = "SELECT * FROM customers ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE customer_id LIKE "%'.$_POST["search"]["value"].'%"
OR customer_name LIKE "%'.$_POST["search"]["value"].'%"
OR customer_store LIKE "%'.$_POST["search"]["value"].'%"
OR customer_address LIKE "%'.$_POST["search"]["value"].'%"
OR customer_phone LIKE "%'.$_POST["search"]["value"].'%"
OR customer_email LIKE "%'.$_POST["search"]["value"].'%"
OR customer_sale LIKE "%'.$_POST["search"]["value"].'%"
OR customer_status LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY customer_date DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$statement = $connect->prepare($query . $query1);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['customer_id'];
$sub_array[] = $row['customer_store'];
$sub_array[] = $row['customer_name'];
$sub_array[] = $row['customer_address'];
$sub_array[] = $row['customer_phone'];
$sub_array[] = $row['customer_email'];
$sub_array[] = $row['customer_status'];
$sub_array[] = $row['customer_date'];
$sub_array[] = $row['customer_order'];
$sub_array[] = $row['customer_sale'];
$sub_array[] = $row['customer_detail'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT * FROM customers";
$statement = $connect->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
'draw' => intval($_POST['draw']),
'recordsTotal' => count_all_data($connect),
'recordsFiltered' => $number_filter_row,
'data' => $data
);
echo json_encode($output);
?>
//ACTION.PHP
<?php
if ($_POST['action']== 'edit') {
$data = array(
':customer_store' => $_POST['customer_store'],
':customer_name' => $_POST['customer_name'],
':customer_address' => $_POST['customer_address'],
':customer_phone' => $_POST['customer_phone'],
':customer_email' => $_POST['customer_email'],
':customer_status' => $_POST['customer_status'],
':customer_id' => $_POST['customer_id']
);
$query = "
UPDATE customers
SET customer_store = :customer_store,
customer_name = :customer_name,
customer_address = :customer_address,
customer_phone = :customer_phone,
customer_email = :customer_email,
customer_status = :customer_status
WHERE customer_id = :customer_id
";
$statement = $connect->prepare($query);
$statement->execute($data);
echo json_encode($_POST);
}
if ($_POST['action'] == 'delete')
{
$query = "
DELETE FROM customers
WHERE customer_id = '".$_POST["customer_id"]."'
";
$statement = $connect->prepare($query);
$statement->execute();
echo json_encode($_POST);
}
?>
My all information here, thank you for your help.
if you need! adding hyperlinks to table column .
I add this code under type:POST in script section
i have 9 table head. i added 1 more 'th' end of the line.
"columnDefs": [ {
"targets": 10,
"data": 0,
"render": function ( data, type, row, meta ) {
return '<center><button class="btn btn-light btn-sm">Detail</button></center>';
}
}]
targets 10 last 'th' ----
data 0 is customer_id.

How to add export to excel pdf buttons in datatable in php

I have fetch some data from database in datatable with edit delete buttons and filtering whole data by custom select option.
Note:- but my requirement is this:-
(1). add export to excel pdf buttons in datatable.
(2). how to add more columns in single row in datatable.
HTML Code:-
<table id="example1" class="display table">
<thead>
<tr>
<th>S.No</th>
<th>Job Title</th>
<th>Experience</th>
<th>Salary</th>
<th>Action</th>
</tr>
</thead>
</table>
jQuery / Ajax code:-
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" rel="stylesheet">
//displaying data on page start here
$(document).ready(function(){
loadDatatableAjax();
});
function loadDatatableAjax(){
$('#example1').DataTable({
"bDestroy" : true,
"ajax" : "ajaxCompany_search.php",
"initComplete" : function(){
var notApplyFilterOnColumn = [4];
var inputFilterOnColumn = [0];
var showFilterBox = 'beforeHeading'; //beforeHeading, afterHeading
$('.gtp-dt-filter-row').remove();
var theadSecondRow = '<tr class="gtp-dt-filter-row">';
$(this).find('thead tr th').each(function(index){
theadSecondRow += '<td class="gtp-dt-select-filter-' + index + '"></td>';
});
theadSecondRow += '</tr>';
if(showFilterBox === 'beforeHeading'){
$(this).find('thead').prepend(theadSecondRow);
}else if(showFilterBox === 'afterHeading'){
$(theadSecondRow).insertAfter($(this).find('thead tr'));
}
this.api().columns().every( function (index) {
var column = this;
if(inputFilterOnColumn.indexOf(index) >= 0 && notApplyFilterOnColumn.indexOf(index) < 0){
$('td.gtp-dt-select-filter-' + index).html('<input type="text" class="gtp-dt-input-filter">');
$( 'td input.gtp-dt-input-filter').on( 'keyup change clear', function () {
if ( column.search() !== this.value ) {
column
.search( this.value )
.draw();
}
} );
}else if(notApplyFilterOnColumn.indexOf(index) < 0){
var select = $('<select><option value="">Select</option></select>')
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
$('td.gtp-dt-select-filter-' + index).html(select);
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
}
});
}
});
}
</script>
ajaxCompany_search.php
<?php
include('../../config.php');
$sql = "SELECT * FROM `jobpost` where `status`=1";
$records = mysqli_query($con,$sql);
$resultList = array();
while ($project = mysqli_fetch_array($records))
{
$resultList[] = $project;
}
$result = array();
$button = '';
$i = 1;
foreach ($resultList as $key => $value) {
$button = '<a class="btn-sm btn-success text-light" onclick="editFun('.$value['id'].')" href="#"> Edit</a> ';
$button .= ' <a class="btn-sm btn-danger text-light" onclick="deleteFun('.$value['id'].')" href="#"> Delete</a>';
$result['data'][] = array(
$i++,
$value['jobtitle'],
$value['experience'],
$value['salary'],
$button
);
}
echo json_encode($result);
?>
Add following code to your datatable function
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
Example
$(document).ready(function() {
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
} );
} );
For details you can check at

Filtering function not working

I've got a table:
And a button named "Aplicar Filtro" that filters the table by whatever I input in the input fields below the header.
The problem is that it's not doing anything and I don't know why, console isn't showing any errors.
Here is my code, pueblaTabla() is specifically the function that filters the table:
<?php
include '../definenachopc.php';
// include '../definegrupo2.php';
$conn = new mysqli($HOST, $USER, $PASS, $DB);
$orderBy = "idAuto";
$order = "desc";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ABM</title>
<link rel="stylesheet" href="style.css">
<script src=".././jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="parte">
<button id="cmdFiltrar">Aplicar filtro</button>
</div>
<div class="parte">
<button id="cmdLimpiaFiltros">Limpiar filtros</button>
</div>
<div class="demo-content">
<div id="demo-order-list">
<?php
$sql = "SELECT * FROM AUTOS";
$result = $conn->query($sql);
$resultadoNumeroDeAutos = $result->num_rows;
?>
<table class="table-content">
<thead>
<tr>
<th onClick="orderColumn('idAuto','desc')">idAuto</th>
<th onClick="orderColumn('Marca','asc')">Marca</th>
<th onClick="orderColumn('Modelo','asc')">Modelo</th>
<th onClick="orderColumn('idTipoDeVehiculo','asc')">idTipoDeVehiculo</th>
<th onClick="orderColumn('FechaDeLanzamiento','asc')">FechaDeLanzamiento</th>
</tr>
<tr>
<td></td>
<td><input type="text" name="filtroMarca" id="filtroMarca"></td>
<td><input type="text" name="filtroModelo" id="filtroModelo"></td>
<td><select id="filtroidTipoDeVehiculo" name="filtroidTipoDeVehiculo">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select></td>
<td><input type="text" name="filtroFechaDeLanzamiento" id="filtroFechaDeLanzamiento"></td>
</tr>
</thead>
<?php
$salidaJson = array("autos" => array());
while ($row = $result->fetch_assoc())
{
$salidaJson['autos'][] = array("idAuto" => $row['idAuto'],
"Marca" => $row['Marca'],
"Modelo" => $row['Modelo'],
"idTipoDeVehiculo" => $row['idTipoDeVehiculo'],
"FechaDeLanzamiento" => $row['FechaDeLanzamiento']);
}
$salidaJson = json_encode($salidaJson);
?>
<tbody id="tbDatos">
</tbody>
</table>
</div>
</div>
<h1>NĂºmero de autos: <?php echo $resultadoNumeroDeAutos; ?></h1>
<script>
var miTabla = $("tbody");
var listaDeAutos = <?php echo $salidaJson ?>;
console.log(listaDeAutos);
// carga la tabla
$(document).ready(function() {
$.each(listaDeAutos.autos, function(i, item) {
var html = '<tr><td>'+ item.idAuto + '</td><td>' + item.Marca + '</td><td>'+ item.Modelo + '</td><td>' + item.idTipoDeVehiculo + '</td><td>' + item.FechaDeLanzamiento + '</td></tr>';
miTabla.append(html);
});
})
function limpiarFiltros() {
$("#filtroMarca").val('');
$("#filtroModelo").val('');
$("#filtroidTipoDeVehiculo").val('');
$("#filtroFechaDeLanzamiento").val('');
};
function orderColumn(column_name,column_order) {
$.ajax({
url: "order-column.php",
data:'orderby='+column_name+'&order='+column_order,
type: "POST",
success: function(data){
$('#demo-order-list').html(data);
}
});
}
function pueblaTabla() {
$("#tbDatos").empty();
$.ajax({
type: "POST",
url: "",
data: {
fMarca: $("#filtroMarca").val(),
fModelo: $("#filtroModelo").val(),
fidTipoDeVehiculo: $("#filtroidTipoDeVehiculo").val(),
fFechaLan: $("#filtroFechaLan").val(),
},
success: function(data) {
$("#tbDatos").empty();
$.each(listaDeAutos.autos, function(i, item) {
var html = '<tr><td>'+ item.idAuto + '</td><td>' + item.Marca + '</td><td>'+ item.Modelo + '</td><td>' + item.idTipoDeVehiculo + '</td><td>' + item.FechaDeLanzamiento + '</td></tr>';
miTabla.append(html);
// /*Nuevo para abm*/
// var objTd = document.createElement("td");
// objTd.innerHTML = "<button>M</button>";
// objTd.onclick = function() {
// var cadenaDePaso = "?ID=" + argValor.ID;
// location.href = "./fichaAbm.php" + cadenaDePaso;
// }
// objTr.appendChild(objTd);
// var objTd = document.createElement("td");
// objTd.innerHTML = "<button>B</button>";
// objTd.onclick = function() {
// var cadenaDePaso = "?ID=" + argValor.ID;
// location.href = "./baja.php" + cadenaDePaso;
// }
// objTr.appendChild(objTd);
});
}
});
}
$("#cmdLimpiaFiltros").click(function() {
limpiarFiltros();
});
$( "#cmdFiltrar" ).click(function() {
pueblaTabla();
});
</script>
</body>
</html>
Add a failure function to the Ajax call...the do console.log...youll get why it's failing if it's the Ajax call

Repeating jquery script in every row in table automatically

I have problem with this script. When I change value in column "TO" in table, script substract automatically in column "Number of hours" only in first row value but others no. I need application script with name "PRO1" (updateDue) in every row in table.
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<body onload="changeText()">
<?php
$date = date('Y-m-01');
$end = date('Y-m-t');
//, strtotime('-1 months')//
?>
<?php include 'dbconfig.php' ?>
<table border="1" id="myTable">
<tr>
<td>Date</td>
<td>From</td>
<td>To</td>
<td>Number of hours</td>
</tr>
<tr class="item">
<?php
date_default_timezone_set('UTC');
while(strtotime($date) <= strtotime($end)) {
$day_num = date('d', strtotime($date));
$day_name= date('l', strtotime($date));
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
if (($day_name == "Saturday")||($day_name == "Sunday"))
{
echo "<td id='color'>$day_num $day_name</td><td></td><td></td><td></td></tr>";
}
else {
echo "<td>$day_num $day_name</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$starter= $query_row['start'];
echo "<input type='text' class='txtCal' id='num1' onchange='updateDue()' value=".$query_row['start'].">";
}
echo "</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$finisher= $query_row['end'];
echo "<input type='text' class='txtCal' id='num2' onchange='updateDue()' value=".$query_row['end'].">";
}
echo "</td><td>";
$ts1 = strtotime($starter);
$ts2 = strtotime($finisher);
$seconds_diff = $ts2 - $ts1;
$time = ($seconds_diff/3600);
echo "<input type='text' class='txtCal2' id='remainingval' value=".number_format((float)$time, 2, '.', '').">";
echo "</td></tr>";
}
}
?>
</tr>
<tr>
<td></td>
<td></td>
<td>Sum:</td>
<td id="total_sum_value"><span id="total_sum_value"></span></td>
</tr>
</table>
<br>
<!-- SCRIPT NAME PRO1 -->
<script>
function updateDue() {
$('#myTable tr').each(function(){
var total = parseFloat(document.getElementById("num2").value);
var val2 = parseFloat(document.getElementById("num1").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
});
}
</script>
<script>
$(document).ready(function changeText(){
$(document).ready(function changeText(){
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
calculated_total_sum += parseFloat(get_textbox_value);
});
$("#total_sum_value").html(calculated_total_sum);
});
$("#myTable").on('change','input', '.txtCal2', function () {
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
});
});
</script>
I want dynamically change table. In column "FROM" and "TO" is value from database. This automatically subtract value (TO-FROM) and sum from this value is down. But when user change some value in column "FROM" or "TO", number will be count automatically. Thank you so much for every advice.
That's because you use the same ID for multiples TDs. You can't do that as an ID is supposed to be used once and help to identify a resource.
instead of an ID, you could use a class :
<table>
...
<tr>
<td><input type="text" class="txtCal num1" value="5" /></td>
<td><input type="text" class="txtCal num2" value="10" /></td>
<td><input type="text" class="txtCal2 remainingval" value="...">
</tr>
...
</table>
Then with jQuery, you can have access to your row values like this :
$('#myTable tr').each(function(){
var total = parseFloat($(this).find('.num2').val());
var val2 = parseFloat($(this).find('.num1').val());
...
var ansD = $(this).find(".remainingval");
ansD.val(total - val2);
});
Also let me point that mysql functions are deprecated and you should not use them anymore. Use PDO instead. (See Why shouldn't I use mysql_* functions in PHP?)

javascript (jQuery) - Single script is not working my in my 2 separate page

I have two separate pages : issuance_filter.php and memo_list.php and 1 script . My problem is, I can't make it work on the issuance_filter.php but works perfect in memo_list.php . But sometimes it works vice versa.
Here's my code :
issuance_filter.php
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script type="text/javascript" class="init">
$(document).ready(function() {
$('#example').DataTable( {
"order": [[ 0, "desc" ]]
} );
} );
</script>
<h2>Issuances</h2>
<table id="example" class="table table-striped table-bordered">
<thead>
<tr>
<th width="8%">ID</th>
<th width="18%">Issuance Type</th>
<th width="18%">Category</th>
<th width="18%">In Charge</th>
<th width="18%">Date Released</th>
<th align="18%">Issuance Title</th>
</tr>
</thead>
<tbody>
<?php
include "../dbconnect/dbconnection2015.php";
mysql_query("SET NAMES utf8");
/////////////////////////////////
/*Values from the other page*/
$type = htmlentities($_POST['type']);
$year = htmlentities($_POST['year']);
$in_charge = htmlentities($_POST['in_charge']);
$category = htmlentities($_POST['category']);
mysql_query("SET NAMES utf8");
if (empty($type) AND !empty($year) AND !empty($category) AND !empty($in_charge)) {
$filter = "WHERE Year = '$year' AND Category = '$category' AND In_Charge = '$in_charge'";
}
elseif(empty($year) AND !empty($type) AND !empty($in_charge) AND !empty($category)){
$filter = "WHERE Issuance_Type = '$type' AND Category = '$category' AND In_Charge = '$in_charge'";
}
elseif(empty($in_charge) AND !empty($year) AND !empty($type) AND !empty($category)){
$filter = "WHERE Year = '$year' AND Category = '$category' AND Issuance_Type = '$type'";
}
elseif(empty($category) AND !empty($year) AND !empty($type) AND !empty($in_charge)){
$filter = "WHERE Year = '$year' AND Issuance_Type = '$type' AND In_Charge = '$in_charge'";
}
elseif(empty($type) AND empty($year) AND !empty($in_charge) AND !empty($category)){
$filter = "WHERE Category = '$category' AND In_Charge = '$in_charge'";
}
elseif(empty($in_charge) AND empty($category) AND !empty($year) AND !empty($type)){
$filter = "WHERE Year = '$year' AND Issuance_Type = '$type'";
}
elseif(empty($type) AND empty($in_charge) AND !empty($year) AND !empty($category)){
$filter = "WHERE Category = '$category' AND Year = '$year'";
}
elseif(empty($category) AND empty($year) AND !empty($in_charge) AND !empty($type)){
$filter = "In_Charge = '$in_charge' AND Issuance_Type = '$type'";
}
elseif(empty($type) AND empty($category) AND !empty($in_charge) AND !empty($year)){
$filter = "WHERE In_Charge = '$in_charge' AND Year = '$year' ";
}
elseif(empty($in_charge) AND empty($year) AND !empty($type) AND !empty($category)){
$filter = "WHERE Category = '$category' AND Issuance_Type = '$type'";
}
elseif(!empty($type) AND empty($year) AND empty($category) AND empty($in_charge)){
$filter = "WHERE Issuance_Type = '$type'";
}
elseif(!empty($year) AND empty($type) AND empty($category) AND empty($in_charge)){
$filter = "WHERE Year = '$year'";
}
elseif(!empty($category) AND empty($year) AND empty($type) AND empty($in_charge)){
$filter = "WHERE Category = '$category'";
}
elseif(!empty($in_charge) AND empty($year) AND empty($category) AND empty($year)){
$filter = "WHERE In_Charge = '$in_charge'";
}
elseif(!empty($type) AND !empty($in_charge) AND !empty($year) AND !empty($category)) {
$filter = "WHERE Issuance_Type = '$type' AND In_Charge = '$in_charge' AND Year = '$year' AND Category = '$category'";
}
else{
$filter = "";
}
// echo $filter;
$sql = "SELECT * FROM issuances $filter ORDER BY Issuance_ID DESC";
$fetch_num_memo = mysql_query($sql);
if ($fetch_num_memo && mysql_num_rows($fetch_num_memo) > 0){
while($row = mysql_fetch_assoc($fetch_num_memo)){
$string = $row['Issuance_Heading'];
echo "<tr>";
echo "<td>".$row['Issuance_ID']."</td>";
echo "<td>".$row['Issuance_Type']."</td>";
echo "<td>".$row['Category']."</td>";
echo "<td>".$row['In_Charge']."</td>";
echo "<td>".$row['Date_Released']."</td>";
echo "<td><a class='filename' href='{$row['URL']}' target='_blank'>{$row['Issuance_Title']}</a></td></tr>";
}
}
else {
# Do Nothing
}
?>
</tbody>
</table>
memo_list.php
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script type="text/javascript" class="init">
$(document).ready(function() {
$('#example').DataTable( {
"order": [[ 0, "desc" ]]
} );
} );
</script>
<h2>Issuances</h2>
<table id="example" class="table table-striped table-bordered">
<thead>
<tr>
<th width="5%">ID</th>
<th width="15%">Issuance Type</th>
<th width="15%">Date Released</th>
<th align="15%">Issuance Title</th>
</tr>
</thead>
<tbody>
<?php
include "dbconnect/dbconnection2015.php";
mysql_query("SET NAMES utf8");
$fetch_num_memo = mysql_query("SELECT * FROM issuances WHERE $filter ORDER BY Issuance_ID DESC");
if ($fetch_num_memo && mysql_num_rows($fetch_num_memo) > 0){
while($row = mysql_fetch_assoc($fetch_num_memo)){
$string = $row['Issuance_Heading'];
echo "<tr>";
echo "<td>{$row['Issuance_ID']}</td>";
echo "<td> {$row['Issuance_Type']}</td>";
echo "<td>".$row['Month'].". ".$row['Date'].", ".$row['Year']."</td>";
echo "<td><a class='filename' href='{$row['URL']}' target='_blank'>{$row['Issuance_Title']}</a></td></tr>";
}
}
else {
echo '<script type="text/javascript">
window.location = "sdo_issuances.php"
</script>';
}
?>
<tbody>
</table>
and the script :
<script type='text/javascript'>
$(document).ready(function(){
$('.filename').click(function(){
var filename = ($(this).text());
$.post('sdo_insert.php', {postname:filename}, function (data) {
// $('.insert').html(data);
});
alert('You clicked : ' + filename);
});
});
</script>
I can't make the script works in both pages and can't figure out the problem. Please help me solve this one. Thanks
try this
<script type='text/javascript'>
$(function() {
$('.filename').click(function(){
var filename = ($(this).text());
$.post('sdo_insert.php', {postname:filename}, function (data) {
// $('.insert').html(data);
});
alert('You clicked : ' + filename);
});
});
</script>

Categories

Resources