jQuery calculation in table td loop - javascript

I am getting the JSON data through PHP. I am trying to calculate the value of td with the help of javascript and jQuery and calculate the opening and closing balance as below like the table example.
is this possible to do that?
Please help me How I implement with jquery in my jQuery code.
Example table -
open bal as 0 first time + today in - today out = closing bal and
previous closing bal will be open bal next day.
open bal
today in
today out
closing bal
1
1
1
1
2
0
1
1
0
2
0
2
$.ajax({
type: "POST",
cache: false,
},
success: function(response) {
if (response == "ok") {
$.each(response.data, function(i, items) {
tableWithHeader.find('tbody').append(`
<tr>
<td>0</td>
<td>${items.inqty}</td>
<td>${items.outqty}</td>
<td></td>
</tr>
`);
});
}
});

Here:
$.ajax({
type: "POST",
cache: false,
},
success: function(response) {
if (response == "ok") {
let openqty = 0 // declare outside of loop
let closeqty = 0 // declare outside of loop
$.each(response.data, function(i, items) {
closeqty = parseInt(items.inqty) - parseInt(items.outqty) + openqty
//calculate closeqty
tableWithHeader.find('tbody').append(`
<tr>
<td>${openqty}</td> // this will be 0 on first run
<td>${items.inqty}</td>
<td>${items.outqty}</td>
<td>${closeqty}</td>
</tr>
`);
});
openqty = closeqty // now set it for next loop to be same as closeqty
}
});
Working example:
//$.ajax({
//type: "POST",
//cache: false,
//},
//success: function(response) {
//if (response == "ok") {
let openqty = 0 // declare outside of loop
let closeqty = 0 // declare outside of loop
const response = {
data: [{
inqty: "2",
outqty: "0"
}, {
inqty: "0",
outqty: "1"
}, {
inqty: "1",
outqty: "1"
}]
} // sample data
$.each(response.data, function(i, items) {
closeqty = parseInt(items.inqty) - parseInt(items.outqty) + openqty
//calculate closeqty
$("table").find('tbody').append(`
<tr>
<td>${openqty}</td> // this will be 0 on first run
<td>${items.inqty}</td>
<td>${items.outqty}</td>
<td>${closeqty}</td>
</tr>
`);
openqty = closeqty // now set it for next loop to be same as closeqty
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
</tbody>
</table>

Related

Can't get Datatables row group working with ajax

I am trying to group rows in my table based on date ranges using the first column's data("Due_Date") and using the rowGroup extension from Datatables. I have searched and tried solutions from others such as using the data property('Due_Date') vs. the index of an array([0]) and removed buttons from table to prevent conflicts. I believe the versions of jQuery, Datatables, and rowGroup extensions are correct. I actually need the table to be split into three groups(red, yellow, and green) based on the table legend.(If "Due_Date" is before, current date, the current date, or 1 or 2 days after the current date, the group = red group. 3-4 days after current date = yellow group, and 5 or more days after current date = green group.) I realize I don't have the correct logic for the grouped date ranges but as of now I can't get the table to group by the data property at all. The table displays data but it seems as if the grouping is being ignored? Apologies in advance, I'm new to this and not sure where I'm going wrong. Any help is appreciated. Here is my relevant code:
//html
<table class="table table-striped" id="circuitsDueTable">
<caption style="caption-side:top">
<ul>
<li><span style="background-color:#ff3333;font-weight:bolder">RED</span> = Current
Date: Plus Two Days</li>
<li><span style="background-color:#ffff4d;font-weight:bolder">YELLOW</span> =
Pending: Three to Four Days</li>
<li><span style="background-color:#4dff4d;font-weight:bolder">GREEN</span> = Have
Time: Five or More Days</li>
</ul>
</caption>
<thead>
<tr>
<th>OCV DUE DATE</th>
<th>CIRCUIT NAME</th>
<th>OCV</th>
<th>CIRCUIT VIEW</th>
</tr>
</thead>
<tbody id="circuitsDueTableBody"></tbody>
<tfoot></tfoot>
</table>
//javascript/jquery
function getTable() {
$.ajax({
url: baseUrl + "VoltReading/GetOCVDue",
method: "POST",
dataType: "json",
success: function(data) {
if (circuitsDueTable) {
circuitsDueTable.destroy();
}
circuitsDueTable = $("#circuitsDueTable").DataTable({
data: data,
order: [
[0, "asc"]
],
rowGroup: {
dataSrc: "Due_Date"
},
columns: [{
data: 'Due_Date'
},
{
data: 'Circuit_Num'
},
{
data: 'Stage_Num'
},
{
render: function(data, type, row) {
return '<button class="btn btn-success btn-xs viewCircuitBtn"
value="' + row.Circuit_Id + '">View Circuit</button></a>';
}
}
],
//return moment(row.Due_Date).format();
});
}
});
}
getTable()
//php controller
public function GetOCVDue()
{
$ocvsDue = $this->ocv->SelectCircuitOCVDates();
echo json_encode($ocvsDue);
}
//json data
[
{"Circuit_Id":"89","Circuit_Num":"090622002C","Due_Date":"2022-09-10","Stage_Num":"1"},
{"Circuit_Id":"90","Circuit_Num":"0909221B","Due_Date":"2022-09-13","Stage_Num":"1"},
{"Circuit_Id":"89","Circuit_Num":"090622002C","Due_Date":"2022-09-14","Stage_Num":"2"},
{"Circuit_Id":"90","Circuit_Num":"0909221B","Due_Date":"2022-09-17","Stage_Num":"2"},
{"Circuit_Id":"88","Circuit_Num":"090622001B","Due_Date":"2022-09-22","Stage_Num":"3"},
{"Circuit_Id":"89","Circuit_Num":"090622002C","Due_Date":"2022-09-22","Stage_Num":"3"},
{"Circuit_Id":"90","Circuit_Num":"0909221B","Due_Date":"2022-09-25","Stage_Num":"3"}
]
Here is a basic approach - I say "basic" because it does not use a library such as Moment or the newer Luxon - but only the built-in Date object:
var today = new Date();
var redDate = today.setDate(today.getDate() + 2);
var yellowDate = today.setDate(today.getDate() + 4);
I use the above dates to calculate a status color for each record, and I add that status value to the JSON results returned from the URL.
Then, I use the rowGroup.dataSrc option to base its grouping on this newly calculated status color:
rowGroup: {
dataSrc: "status"
}
The full JavaScript is as follows:
$(document).ready(function() {
function getTable() {
$.ajax({
url: "YOUR URL GOES HERE", // I used my own test URL
method: "POST",
dataType: "json",
success: function(data) {
if (circuitsDueTable) {
//circuitsDueTable.destroy();
}
var today = new Date();
var redDate = today.setDate(today.getDate() + 2);
var yellowDate = today.setDate(today.getDate() + 4);
data.forEach(function(row) {
var date = Date.parse(row.Due_Date);
var color = 'green'; // default for 5 or more days
if ( date <= redDate ) {
color = 'red';
} else if ( date <= yellowDate ){
color = 'yellow';
}
row['status'] = color; // add color to row
});
circuitsDueTable = $("#circuitsDueTable").DataTable({
data: data,
order: [
[0, "asc"]
],
rowGroup: {
dataSrc: "status"
},
columns: [{
data: 'Due_Date'
},
{
data: 'Circuit_Num'
},
{
data: 'Stage_Num'
},
{
render: function(data, type, row) {
return '<button class="btn btn-success btn-xs viewCircuitBtn" value="' + row.Circuit_Id + '">View Circuit</button></a>';
}
}
],
//return moment(row.Due_Date).format();
});
}
});
}
getTable()
} );
And the resulting table looks like this:

Two separate ajax calls with one running in an interval but depending on the other to stop

I have got two calls that have to run in parallel. One is supposed to continuously fetch data and update a table and it should only stop when the result of the other ajax function is returned. I use setinterval() funtion to run the continuous fetching. For some reason, the results of the continuously fetched data only come later after the single call of the second ajax function has completed. Here is my code.
function runNightly() {
let timer = null;
$.when(
timer = setInterval(updateServicesTable, 500),
$.ajax({
type: "POST",
url: "EndOfDay.asmx/runEOD",
contentType: "application/json",
success: function (responseFromServer) {
$.each(responseFromServer, function (index, res) {
console.log("EOD result :" + res);//Result from EOD
});
},
complete: function () {
setTimeout(stopTask, 0, timer);
},
failed: function () {
setTimeout(stopTask, 0, timer);
}
})
).then(function () {
console.log('Done');
});
}
Here is my code for continuously fetching data:
function updateServicesTable() {
console.log("fetch services");
$.ajax({
type: "POST",
url: "EndOfDay.asmx/fetchServices",
contentType: "application/json",
success: function (responseFromServer) {
var row = $("[id*=ServicesGrid] tr:last-child").clone(true);//Get the last row, its always a null
$("[id*=ServicesGrid] tr").not($("[id*=ServicesGrid] tr:first-child")).remove();//remove all rows except the last
let objdata = $.parseJSON(responseFromServer.d);
console.log(objdata);//results obtained
if (objdata != null) {
let table = objdata["Table1"];
let rowNum;
for (rowNum in table) {
if (table[rowNum] != null) {
/*Update the row variable*/
$("td", row).eq(0).html(table[rowNum][0]);//code
$("td", row).eq(1).html(table[rowNum][1]);//descriptions
$("td", row).eq(2).html(table[rowNum][2]);//process flag
$("td", row).eq(3).html(table[rowNum][6]);//status code
$("[id*=ServicesGrid]").append(row);//append the row to the gridview
row = $("[id*=ServicesGrid] tr:last-child").clone(true); //get the new last row
}
}
}
},
complete: function () {
console.log("calling services complete");
},
});
}

How to get the data from ajax in controller codeigniter

I have an editable table in my view.. At first, there's no data in the table but the user can add data in the table since it is editable. And there's no exact number of rows in the table since I have also a button that can add new row. I want to get the data that the user have added and save it in the database.
I have this code:
VIEW:
<table class="table " id="memberTB">
<thead><tr><th >First Name</th><th >Middle Name</th><th>Last Name</th></tr></thead>
<tbody>
<tr id="first"><td><span class="edit"></span></td>
<td><span class="edit"></span></td>
<td><span class="edit"></span></td></tr>
</tbody>
<button type="button" class="btn btn-link" id="addrow"><span class="fa fa-plus"> Add new row</span></button>
</table>
<br><button type="button" class="btn" id="savebtn">Save</button> Reset
JS:
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.showbuttons = false;
$.fn.editable.defaults.url = '/post';
$.fn.editable.defaults.type = 'text';
// make all items having class 'edit' editable
$('.edit').editable();
// this is to automatically make the next item in the table editable
$('.edit').on('save', function(e, params){
var that = this;
// persist the old value in the element to be restored when clicking reset
var oldItemValue = $(that)[0].innerHTML;
if (!$(that).attr('oldValue')) {
console.log('persisting original value: ' + oldItemValue)
$(that).attr('oldValue', oldItemValue);
}
setTimeout(function() {
// first search the row
var item = $(that).closest('td').next().find('.edit');
console.log(item);
if (item.length == 0) {
// check the next row
item = $(that).closest('tr').next().find('.edit');
}
item.editable('show');
}, 200);
});
$('#resetbtn').click(function() {
$('.edit').each(function() {
var o = $(this);
o.editable('setValue', o.attr('oldValue')) //clear values
.editable('option', 'pk', o.attr('pk')) //clear pk
.removeClass('editable-unsaved')
.removeAttr('oldValue');
});
});
$('#savebtn').click(function() {
var person = [];
var x=1;
$('tbody tr',$('#memberTB')).each(function(){
for(var i = 0 ; i < cells ; i++)
{
person[x][i]=$(this).find('td').eq(i).text();
}
x++;
});
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: { values: arraylng },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
});
$('#addrow').click(function() {
$('#memberTB > tbody:last').append(' <tr><td><span class="edit"></span></td><td><span class="edit"></span></td><td><span class="edit"></span></td></tr>');
$('.edit').editable();
});
Controller: [inside the test.php]
public function saveData(){
$this->load->model('test_model');
$myArray = $_REQUEST['values'];
echo sizeof($myArray);
}
Whenever I click the save button, there's no response at all.. Where did I go wrong? please help me..
ADDED INFO:
I didn't include my SQL insert statement here because I want to test first if there's data in $myArray if I added data in the table.
Better use this ajax
var arraylng = [3,4,7];
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: {values: JSON.stringify(arraylng)},
cache: false,
success: function (response) {
alert(response);
}
});
arraylng is an array, which doesn't exist in the code. I added it here for debugging.
Suppose you want to send person[] array, you write, data: {values: JSON.stringify(person)}.
Now, the person array may not exist, because of the "i < cells" in for. What is cells?
The word response is just a name, any name, but better avoid 'data'.
In test.php, what is sizeof($myArray)? Just, echo $myArray;
When you click save you must get the $myArray content in an alert.

jquery each function on string variable

I have wrote a function in javascript which takes title attributes of <tr> calls ajax then after some operation it retreive some title attributes from them. depending on that title attribute i want to remove those <tr> rows
function currentTicketStatus() {
var ids = '';
$('tbody tr[title]').each(function() {
ids += ((ids == '') ? '' : ',') + $(this).attr('title');
});
$.ajax({
url: 'ajaxExecute.aspx?Fn=CTS',
type: 'POST',
context: document.body,
cache: false,
data: 'Tickets=' + ids,
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
sTickets.each(function() {
$(this).parent().parent().remove();
});
}
}
}
});
}
Example : at the time of ajax call ids="100,101,102,103,104" after ajax call sTickets="101|102" . Now remove those rows with attributes of sTickets
HTML (Not Exactly )
<tbody>
<tr title="100"> some data part </tr>
<tr title="101"> some data part </tr>
<tr title="102"> some data part </tr>
<tr title="103"> some data part </tr>
</tbody>
the this in the each is a "title" (a string), you need the DOM element (the <tr>) instead
sTickets.each(function() {
$('tbody tr[title="'+ this +'"]').remove();
});
demo
try this code in your success function :
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
$.each(function(i,v){ $('tr[title=' + v + ']') }).remove();
}
}
Explanation:
1- SELECT DOM element by attribute :
$('[ATTRIBUTE=VALUE]') // $('[title="myTitle"]')
you can find more in this link http://api.jquery.com/attribute-equals-selector/
2 - $.each Iteration
which can be used to seamlessly iterate over both objects and arrays.
more : http://api.jquery.com/jquery.each/

Please help optimize and write Jquery function that gets json data and appends it to select list options

Basically just need to write a jQuery/Ajax that fetches Json data (Price data) from server
and appends/overwrites each options text value so it would have the price difference between the
selected option and non selected option on the end of it. Only the non selected option should have the price difference showing on the end of it, see example below.
The code you will find below pretty much does this, but I can't seem to properly append/overwrite
it to the end of the option text value without the price difference being repeated (not replaced) onto the end with every onchange of the dropdown list. So I get [product name025252525] etc.
As well no idea how to not append the difference to the selected options text, I just get "0" there now as it minuses itself from itself.
The Json object (data) array is of the format {partid = 3, price = 234}, {partid = 6, price = 53} etc.
List should look like so:
[Intel i7 950] - selected visible option
[Intel i7 960 (+ $85)] - not selected but in the drop down list
[Intel i7 930 (- $55)] - not selected but in the drop down list
<script type="text/javascript">
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { mydata = data; OnSuccess(data) },
dataType: "json"
});
});
$('select').change(function () { OnSuccess(mydata); });
function OnSuccess(data) {
$('select').each(function () {
var sov = parseInt($(this).find('option:selected').attr('value')) || 0; //Selected option value
var sop; //Selected Option Price
for (i = 0; i <= data.length; i++) {
if (data[i].partid == sov) {
sop = data[i].price;
break;
}
};
$(this).find('option').each(function () {
// $(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
var newtext = uop - sop;
var xtext = $(this).text().toString();
$(this).attr("text", xtext + newtext);
// mob.append(newtext)
// $(this).next('span').html(newtext);
});
});
};
//$(document).ready(function () { $("#partIdAndCount_0__PartID").prepend('<option value="0">Select Processor<option>'); });
</script>
You are close:
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: OnSuccess,
dataType: "json"
});
OnSuccess is a function taking one parameter, data. So you simply use that method like above.
$('select').change(OnSuccess(data);); would compile if fixed like $('select').change(OnSuccess(data)); , minus the semicolon in the function. However, this is executing OnSuccess immediately. So again, $('select').change(OnSuccess); is what you want.
Declare a variable to store it in the outer scope:
var theJSON;
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
$.ajax({
type: "POST",
url: "/Customise/GetPartPrice",
data: { arr: arr },
traditional: true,
success: function (data) { theJSON = data; OnSuccess(theJSON)},
dataType: "json"
});
});
$('select').change(function(){ OnSuccess(theJSON); });

Categories

Resources