I have created DataTable, am getting all data from API but I need destroy and recreate every 10seconds am using setInterval function but reload do not reload and every 10second destroy and recreate. Is possible, I am trying more reference but could not solve this issue and also attached code below please check my code and solve this issue
my code:
staffTransaction()
function staffTransaction(){
var todayDate = new Date();
var dd = String(todayDate.getDate()).padStart(2, '0');
var mm = String(todayDate.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = todayDate.getFullYear();
to_date = dd + '-' + mm + '-' + yyyy;
var date = new Date();
date.setDate(date.getDate() - 7);
var from_date = date.getDate()+'-'+ (date.getMonth()+1) +'-'+date.getFullYear();
var offerType = $('#offerType option:selected').val();
// alert(offerType)
var transStaff = {
"admin_id": localStorage.getItem("admin_id"),
"role": localStorage.getItem("role"),
"offer_type": 'znapay',
"from_date": from_date != undefined && from_date != "" ? from_date : "",
"to_date": to_date != undefined && to_date != "" ? to_date : "",
"store_id": localStorage.getItem('store-ids'),
"branch_id": localStorage.getItem('store_branch')
}
console.log(transStaff)
console.log('Staff' + JSON.stringify(transStaff))
fetch('https://app/api/v6/manager/transactions-web', {
method: "POST",
body: JSON.stringify(transStaff),
headers: {
'Content-Type': 'application/json',
'accept': 'application/json'
},
}).then(function(test) {
return test.json()
}).then(function(callback) {
$('#transaction-lists').html("")
$("#transaction-dates").html("Transactions from " + callback.from_date + " to " + callback.to_date)
var ListTransation = "";
var transList = callback.transaction_list;
if (callback.transaction_list.length == 0) {
$('.not-found').html("<p>Data Not Found");
ListTransation = "<tr><td colspan='7' align='center'>No Transactions</td></tr>"
$('#transaction-lists').html(ListTransation);
} else {
var mapList = transList.map(function(x, y) {
if (y == 0) {
localStorage.setItem("last_transaction", x.transaction_id)
}
var email_help = x.elapsed_time <= 1800 ? "<img src='assets/images/email.png'>" : ""
// var email_help = x.elapsed_time <= 1800 ? "<i class='fa fa-envelope-o email-help' aria-hidden='true'></i>" : ""
// <i class="fa fa-envelope-o" aria-hidden="true"></i>
ListTransation += "<tr id=" + x.transaction_id + ">";
ListTransation += "<td class='reference-id'>" + x.reference_id + "</td>";
ListTransation += "<td>" + x.date + "</td>";
ListTransation += "<td>" + x.offer_type_label + "</td>";
ListTransation += "<td>" + x.offer_class + "</td>";
ListTransation += "<td>" + x.store_location + ", " + x.store_city + "</td>";
ListTransation += "<td class='bill-amount' style='text-align:center!important'>AED " + parseFloat(x.bill_amount).toFixed(2) + "</td>";
ListTransation += "<td>" + email_help + "</td>";
ListTransation += "</tr>";
});
$('#transaction-lists').html(ListTransation);
table = $('.staff-transtable').DataTable( {
destroy: true,
paging: false
} );
table.destroy();
setTimeout(function(){
table1 = $('.staff-transtable').DataTable( {
searching: true,
retrieve: true,
paging: true
} );
},2000)
}
});
}
Related
I am trying to complete my code that dynamically produces a table using Jquery DataTables plugin.
The code works up to a point, it displays the data but above the data it also displays "No data available in table".
From what I have read it is something to do with the table initialisation, Can anyone see where I am going wrong.
$(document).ready(function(){
$('#userTable').DataTable( {
"ordering": false,
paging: false,
searching: false,
language: {
emptyTable: "No data available in table", //
loadingRecords: "Please wait .. ", // default Loading...
zeroRecords: "No matching records found"
},
"stripeClasses": [ 'odd-row', 'even-row' ]
});
$.ajax({
url: 'server_processing.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var recordid = response[i].RecordID;
var deviceid = response[i].DeviceID;
var mediatype = response[i].MediaType;
var screenlocation = response[i].ScreenLocation;
var promotionname = response[i].PromotionName;
var fromdate = response[i].FromDate;
var fromtime = response[i].FromTime;
var todate = response[i].ToDate;
var totime = response[i].ToTime;
var promotionimage = response[i].PromotionImage;
var orientation = response[i].Orientation;
var enddate = todate +' '+totime;
var startdate = fromdate +' '+fromtime;
var now = new Date();
var nowdate = fixDigit(now.getDay()) + '-' +fixDigit(now.getMonth() + 1) + '-' + now.getFullYear()+' ' +now.getHours() + ":" + now.getMinutes();
// Utility function to prepend zeros to single digits:
function fixDigit(val){
return val.toString().length === 1 ? "0" + val : val;
}
var tr_str = "<tr class='TableText'>" +
"<td style='color:#333;font-size:0.8em;'>" + promotionname + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + deviceid + " " + screenlocation + "</td>" +
"<td align='center' style='color:#333;font-size:0.8em;'>" + orientation + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + promotionimage + "</td>" +
"<td align='center' style='color:#333;font-size:0.8em;'>" + mediatype + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + fromdate + "</td>" +
"<td style='color:#333;font-size:0.8em;'>" + todate + "</td>"
if( (new Date(startdate).getTime() > new Date(nowdate).getTime())) {
tr_str += "<td align='center' style='color:#333;font-size:0.8em;' class='Active'>Active</td>";
} else {
tr_str += "<td align='center' style='color:#333;font-size:0.8em;' class='Scheduled'>Scheduled</td>";
}
tr_str += "<td align='center' style='color:#333;font-size:0.8em;'><input type='button' name='edit' value='Edit' id=" + (i+1) + " class='btn btn-info btn-xs btn-block edit_data'></td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
});
Many thanks in advance for you help and time.
This is because you are appending content without deleting previous, "no data" massage is a row, so you should clear it before for loop:
success: function(response){
var len = response.length;
$("#userTable tbody").html("");
for(var i=0; i<len; i++){
var recordid = response[i].RecordID;
var deviceid = response[i].DeviceID;
...
One thing, this is not the best way to insert data in datatables.
One more thing is here that if I use the alert() at end of the ajax code the code is working fine. here whatever the ajax response comes has to be appended to the existing table.
for (var i = 1; i < rows.length; i++) {
var cells = splitCSVtoCells(rows[i], ",");
var obj = {};
for (var j = 0; j < cells.length; j++) {
obj[first_Row_Cells[j]] = cells[j];
}
jsonArray.push(obj);
}
console.log(jsonArray);for (var i = 0; i < jsonArray.length-1; i++) {
html += "<tr id=\"rowitem" + i + "\"><td id=\"rownum"+i+ "\" style=\"display:none;\">" + i + "</td><td> " + jsonArray[i].Clientgroup + " </td>";
html += "<td>" + jsonArray[i].hostgroup + "</td>";
html += "<td>" + jsonArray[i].server + "</td>";
html += "<td>" + jsonArray[i].Group + "</td>";
html += "<td>" + jsonArray[i].user + "</td>";
html += "<td>" + jsonArray[i].ticket + "</td>";
html += "<td>" + jsonArray[i].requesttype + "</td>";
$.ajax({
url : "BulkValidateServlet",
type : "POST",
data : {clientgroup: jsonArray[i].Clientgroup, hostgroup: jsonArray[i].hostgroup, server: jsonArray[i].server
},success : function(response){
//alert("i in of ajax:"+i);
status = response;
if (status) {
//alert("outside if: " + status);
//$('<img src=\'images/check_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/check_mark.png' height='20' width='20'/></td>";
} else {
//alert("outside else: " + status);
//$('<img src=\'images/cross_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/cross_mark.png' height='20' width='20'/></td>";
}
console.log("Data: " + status);
// alert("Data: " + status );
//return status;
}
});
console.log("outside: " + status);
alert();
}
document.getElementById('tbodyLeads').innerHTML = html;
}
You can try adding
async: false
to your ajax attributes.
Refer to this link.
I am written a code something like this.. It is working fine in Mozilla Firefox where as in google chrome without writing any content in the document it is printing.. Please help me how to resolve this problem.
Suppose if I removed that printing statement then it is working fine but I need to print that window
function prepareInvoice(userDetails, courseId)
{
var a = "";
a = a+"<html><head><title>Invoice | Palle University</title>";
a = a + "<link href=\"../assets/css/bootstrap.css\" rel=\"stylesheet\" />";
//form=form+
a = a + "</head><body><header id=\"header\" class=\"navbar-fixed-top\"> <div class=\"container\" > <div class=\"row\" ><div class=\"col-lg-6 col-md-6 col-sm-6 col-xs-6 logo-wrapper\">";
a=a+" <div class=\"pulogo\"><label style=\"color:white\">Palle<sup>®</sup></label>University</div>";
a = a + "</div><div style=\"font-weight:bold;\" class=\"col-lg-6 col-md-6 col-sm-6 col-xs-6 text-right\">Invoice</div></div></div></header>";
a = a + "<section id=\"about\" class=\"clearfix\">";
a = a + "<div class=\"container\" > <div class=\"row\" ><div class=\"col-lg-6 col-md-6 col-sm-6 col-xs-6\">";
a = a + "manish complex;<br>Mangammana palya main road;<br>Bommanahalli-560068;<br>Bangalore;Karnataka-India";
a = a + "</div><div class=\"col-lg-6 col-md-6 col-sm-6 col-xs-6\">";
a = a + "<b>Customer Details:</b><br>";
if (userDetails.Lastname != "")
a = a + "Last Name:" + userDetails.Lastname + "<br>";
if (userDetails.FirstName != "")
a = a + "First Name:" + userDetails.FirstName + "<br>";
if (userDetails.Address != "")
a += "address:" + userDetails.Address + "<br>";
if (userDetails.CityName != "")
a += "city:" + userDetails.CityName + "<br>";
if (userDetails.State != "")
a += "state:" + userDetails.State + "<br>";
if (userDetails.CountryName != "")
a += "Country:" + userDetails.CountryName + "<br>";
if (userDetails.Email != "")
a += "email:" + userDetails.Email + "<br>";
a = a + "</div></div></div>";
a = a + "<div class=\"container\" > <div class=\"row\"> <div class=\"col-lg-12 col-md-12 col-sm-12 col-xs-12\">";
a = a + "<table style=\"font-size:15px\" class=\"table table-responsive table-condensed table-striped table-hover no-margin text-center\"><thead><tr class=\"text-center\"><td>Course Name</td><td>Purchased On</td><td>Expires On</td><td>Amount</td></tr></thead><tbody>";
var cur_symbol='';
var amount=0;
for (i = 0; i < userDetails.LstCourses.length;i++)
{
if (courseId == userDetails.LstCourses[i].CourseId) {
var monthNames = ["jan", "feb", "march", "april", "may", "june",
"July", "aug", "sep", "oct", "nov", "dec"];
a = a + "<tr><td>" + userDetails.LstCourses[i].Course_displayname + "</td>";
var d = new Date(parseInt(userDetails.LstCourses[i].Paid_date.substr(6)));
var curr_date = d.getDate();
var curr_month = monthNames[d.getMonth()];
var curr_year = d.getFullYear();
var cur_symbol = '';
if (userDetails.LstCourses[i].Currency_code.toLowerCase() == "usd")
cur_symbol = "usd ";//"<i class=\"fa fa-usd\"></i>";
else if (userDetails.LstCourses[i].Currency_code.toLowerCase() == "inr")
cur_symbol = "inr ";//"<i class=\"fa fa-inr\"></i>";
a = a + "<td>" + curr_date + "-" + curr_month + "-" + curr_year + "</td>";
d = new Date(parseInt(userDetails.LstCourses[i].Expire_date.substr(6)));
curr_date = d.getDate();
curr_month = monthNames[d.getMonth()];
curr_year = d.getFullYear();
a = a + "<td>" + curr_date + "-" + curr_month + "-" + curr_year + "</td>";
amount = userDetails.LstCourses[i].Amount_paid;
a = a + "<td>" + cur_symbol + userDetails.LstCourses[i].Amount_paid + "</td></tr>";//display dollar or inr symbol.
//display the total amount based on the course id and a thank you ! message .
}
}
a = a + "<tr><td></td><td></td><td></td><td>Total: " + cur_symbol +" "+ amount + "</td></tr>";
a = a + "</tbody></table></div></div></div>";
a = a + "<div class=\"container\" > <div class=\"row\"> <div class=\"col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center\">";
a = a + "Thank you !</div></div></div>";
//a = a + "<table><tr><td></td><td></td><td></td><td>Total:" + cur_symbol + amount + "</td></tr></table></div></div></div>";
a = a + "</body></html>";
//a.print();oUser.Lastname; oUser.Lastname;oUser.Address;
//oUser.Email; oUser.CityName; oUser.State; oUser.CountryName;
debugger;
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write(a);
mywindow.document.close();
mywindow.focus();
mywindow.print();
}
Try this for a div content
function printDivision() {
var printContents = document.getElementById('divId').innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = "<div align='center' style='padding: 5%;' >"
+ printContents + "</div>";
window.print();
document.body.innerHTML = originalContents;
}
I have written JavaScript which retrieves data and sets it into a series of tables as shown below.
$(function()
{
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'9BBF789F-E5BA-449D-A595-BAA326E2C8FF')/Items?$expand=Category&$select=Id,Related_x0020_Working_x0020_PracId,Title,Reference,Policy_x0020_Type,Category/Title&$orderby=Category/Title asc",
type:"get",
headers: { "accept": "application/json;odata=verbose" },
success: function(dataObj)
{
//to uniquely identifiy the accordion.
var intCat = 0;
var arrPolicies = [];
var arrCategories = [];
//Get the policies and seperate out the categories from the returned REST call
for(var i =0; i < dataObj.d.results.length; i++)
{
var strCategory = dataObj.d.results[i].Category.Title;
arrPolicies.push({
"Id" : dataObj.d.results[i].Id,
"Title" : dataObj.d.results[i].Title,
"Category" : strCategory,
"Ref" : dataObj.d.results[i].Reference,
"PolicyType" : dataObj.d.results[i].Policy_x0020_Type,
"WorkingPracticeId" : dataObj.d.results[i].Related_x0020_Working_x0020_PracId
});
//setting category if not found
//in array
if(arrCategories.indexOf(strCategory) == -1)
{
//Add the category to the list...
arrCategories.push(strCategory);
}
}
//Output the menu to the screen for each category - one by one
arrCategories.forEach(function(varCategory)
{
var strCatIdentifier = "tblCategory_" + intCat;
var strCatImgIdentifier = "tblCategory_image_" + intCat;
var strCategoryInfo = "<table>"+
"<tbody>" +
"<tr>"+
"<td class='category'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatIdentifier + ","+strCatImgIdentifier+")'>"+
"<img id='"+strCatImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand category'/>"+
"</a> "+
varCategory +
"</td>"+
"</tr>"+
"<tr><td>"+
"<table id='" + strCatIdentifier + "' class='indent hidden'>";
//looping through policies - add the details into the category table's cell
arrPolicies.forEach(function(varPolicy)
{
//checking the category attached to the policy is the same as what
//category it is on
if(varPolicy.Category == varCategory)
{
//checking to see if the
if(varPolicy.PolicyType == "Policy and Responsibility")
{
strCategoryInfo += "<tr>"+
"<td class='policy'>" +
"<a href='#'>"+
"<img src='"+_spPageContextInfo.webAbsoluteUrl+"/SiteAssets/Images/arrowicon.png' alt='View Document'/>"+
"</a>"
+ varPolicy.PolicyType + ": "+varPolicy.Ref +" - " + varPolicy.Title +
"</td>"+
"</tr>";
}
//If Working Practice - add in the sub-table (3rd level table) for attachments
if(varPolicy.PolicyType == "Working Practices")
{
var strCatWPIdentifier = "tblWorkingPractice" + varPolicy.Id;
var strCatWPImgIdentifier = "sub_level_image" + varPolicy.Id;
strCategoryInfo += "<tr>"+
"<td class='working_practice'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatWPIdentifier + ","+strCatWPImgIdentifier+")'>"+
"<img id='"+strCatWPImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand working practice'/>"+
"</a> "+
varPolicy.PolicyType + " - " + varPolicy.Title+
"</td>"+
"</tr>";
var intAttachmentCount = 0;
//Build a table by looping through the policies array AGAIN and only use the policies where the Policy Type is 'Attachment' AND the 'WorkingPracticeID' is the same as the pilocy ID
arrPolicies.forEach(function(varWPAttachment)
{
if(varWPAttachment.WorkingPracticeId == varPolicy.Id && varWPAttachment.PolicyType == "Working Practice Attachment")
{
intAttachmentCount++;
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
varWPAttachment.PolicyType +" - "+ varWPAttachment.Title+ " - " + varPolicy.Title+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
});
if(intAttachmentCount == 0)
{
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
"Sorry, no attachments found for this practice."+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
}
}
});
//Close the 'Category details' table
strCategoryInfo += "</table>";
//Close the table for the category...
strCategoryInfo += "</td></tr>" +
"</tbody>"+
"</table>";
intCat++;
$('#divQualityFrameworkMenu').append(strCategoryInfo + "<br />");
});
},
error: function(error)
{
alert("Error");
}
});
});
I want to be able to organise them so that related data is grouped together ie Policies are above working practices.
How would I go about doing this
This seems pretty easy. After the first for (var d = 0; [...] ) loop, but before the arrCategories.forEach([...]), just sort arrPolicies to your choosing:
arrPolicies.sort(function(policy1, policy2) {
//Policies BEFORE Working Practicies:
if (policy1.PolicyType === "Policies and Responsibilities" && policy2.PolicyType === "Working Practices") {
return -1;
}
//Working Practicies AFTER Policies:
if (policy1.PolicyType === "Working Practices" && policy2.PolicyType === "Policies and Responsibilities") {
return 1;
}
//[Include any other orderings you might have...]
//If you've reached the end here, then you must not care about the ordering of these policies, so just make them "equal":
return 0;
});
I have this script to get the historical data from last year to today. The script is running good with one stock (in this example "mo"). I build an array because I want 6 stocks and the loop needs to build 6 tables. If I replace the stock name "mo" with my array name I get error.
var yyyy = new Date().getFullYear();
var mm = new Date().getMonth() + 1;
if (mm < 10) {
mm = "0" + mm;
}
var dd = new Date().getDate();
var endDate = yyyy + "-" + mm + "-" + dd;
var startDate = (yyyy - 1) + "-" + mm + "-" + dd;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.historicaldata where symbol = 'mo' and startDate = '" + startDate + "' and endDate = '" + endDate + "'&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback=",
dataType: 'json',
success: function (data) {
var myTable = "";
myTable += "<br /><table border='1' cellpadding='0' cellspacing='0' width='500' bgcolor='green'>";
myTable += "<tr>";
myTable += "<td>Date</td><td>Open</td><td>Low</td><td>High</td><td>Volume</td><td>Close Price</td>";
myTable += "</tr>";
$.each(data.query.results.quote, function (index, item) {
myTable += "<tr><td>" + item.Date + "</td><td>" + item.Open + "</td><td>" + item.Low + "</td><td>" + item.High + "</td><td>" + item.Volume + "</td><td>" + item.Close + "</td></tr>";
});
myTable += "</table>";
$("#quotes").html(myTable);
},
error: function () {
$("#quotes").html('<p>Something has gone terribly wrong.</p>');
}
});
You don't need to build 6 table queries. You can use the "IN" keyword. Sample query if you want historical data for "YHOO", "GOOG" and "AAPL" stock
select * from yahoo.finance.historicaldata where symbol IN ("YHOO","GOOG","AAPL") and startDate = "2009-09-11" and endDate = "2010-03-10"
Test it out in YQL console here