How to fix data table initialization error? - javascript

I have written one function that makes one ajax call and gets the data and creates a table.I calling this function again and again.But while doing that I am getting reinitialization of table error.Can someone please help me to fix the issue.
Function :
function getLibraryFilesStudent() {
var reqBody = {
"uploader": Cookies.get('user')
};
$.ajax({
url: '../library/libraryfilegetlist',
data: JSON.stringify(reqBody),
dataType: 'json',
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
error: function(data) {
console.log(data);
},
success: function(data) {
if (data.length) {
var trHTML = [];
for (var i = 0; i < data.length; i++) {
var test = '<input type="radio" class="radio" name="selectFile" value=' + data[i].id + "," + data[i].keyword + ",flag=1" + '>';
trArr = [data[i].name, data[i].keyword, test]
trHTML.push(trArr);
if (data.length == trHTML.length) {
$('#lFileList').DataTable({
data: trHTML,
bSort: false,
pageLength: 4,
columns: [{
title: "Name"
},
{
title: "keyword"
},
{
title: "Action"
}
]
});
}
}
}
},
type: 'POST'
});
}

Related

Field name is in JSON but datatables don't recognise it?

The error message is as below:
Requested unknown parameter 'emPONumber' for row 0, column 0
But emPONumber is in the JSON, why datatables still prompt this error?
<script type="text/javascript">
$(document).ready(function () {
var tableId = 'tablePurchaseOrders';
var table = $('#' + tableId).DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/GetAllUploadedPurchaseOrders',
type: 'GET',
data: function (data) {
//debugger;
var model = {
draw: data.draw,
start: data.start,
length: data.length,
columns: data.columns,
search: data.search,
order: data.order
};
return model;
},
failure: function (result) {
debugger;
alert("Error occurred while trying to get data from server: " + result.sEcho);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Error occurred while trying to get data from server!");
},
dataSrc: function (json) {
var _data = JSON.stringify(json.Data);
debugger;
return _data;
}
}
,
"columns": [
{ "data": "emPONumber", title: "emPONumber" },
{ "data": "ASMPONumber", title: "ASMPONumber" },
{ "data": "material", title: "material" }
]
});
});
</script>
json in dataSrc: function (json):
{"ContentEncoding":null,"ContentType":null,"Data":{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"emPONumber":"EM1234567","ASMPONumber":"A741000013","material":"26-00010","quantity":5,"UOM":"EA","asmPOQuantity":5,"createBy":"m","ASMPOYear":2018,"ASMPOMonth":6,"ASMPOVendor":"10008"}]},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}
json (_data) return by ajax in dataSrc:
{
"draw":1,
"recordsTotal":1,
"recordsFiltered":1,
"data":
[{
"emPONumber":"EM1234567",
"ASMPONumber":"A741000013",
"material":"26-00010",
"quantity":5,
"UOM":"EA",
"asmPOQuantity":5,
"createBy":"m",
"ASMPOYear":2018,
"ASMPOMonth":6,
"ASMPOVendor":"10008"
}]
}
Try
dataSrc: function (json) {
for(key in json.Data){ json[key] = json.Data[key]; }
delete json['Data'];
return json.data;
}

How to Update Datatable automatically after dialog box is closed in Javascript

Here I have two JS files in which one is main JS file for parent page which contains Datatable which gets populated through ajax call. And other one is specifically for update functionality in which function is defined to update required values into database. That update is done in dialog box. So after successful update sweet alert comes which shows product is successfully updated. So what I want is updated values should be immediately reflected in Datatable of Parent Page. Currently it is showing old value only untill I refresh my page manually. Below are both JS files. And I am new in Javascript and Jquery. So Please help
var oTable;
var url_data_source;
(function(window, undefined) {
window.lastQuery = null;
function initDataSource(after_id) {
url_data_source = '/event/productlocation/ajax?action=data_source';
oTable = $('#datatable').dataTable({
"sAjaxSource": url_data_source,
"bProcessing": true,
"bServerSide": true,
"bFilter": false,
"bRetrieve": true,
"bScrollCollapse": true,
"iCookieDuration": 60*60*24,
"sCookiePrefix": "tkpd_datatable_",
"sPaginationType": "simple",
"scrollX": true,
"aaSorting": [ [0,'desc'] ],
"iDisplayLength": 20,
"aLengthMenu": [[20, 40, 60, 80, 100], [20, 40, 60, 80, 100]],
"oLanguage": {
"sInfoFiltered": "",
"sProcessing": " "
},
"aoColumns": [
{ "sName": "id", "mDataProp": "id"},
{ "sName": "location_id", "mDataProp": "location_id"},
{ "sName": "product_id", "mDataProp": "product_id"},
{ "sName": "status_str", "mDataProp": "status_str"},
{ "sName": "actions", "mDataProp": "actions"},
],
"fnDrawCallback":function(){
},
"initComplete": function(settings, json) {
$("#datatable_paginate").on("click", "#datatable_next", function(){
var after_id = ""
url_data_source = '/event/productlocation/ajax?action=data_source';
after_id_url = $("#after_id_url").val();
after_id = after_id_url.split("after_id=")
url_data_source += "&after_id="+after_id[1];
redraw();
});
},
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( {"name": "email", "value": $('#search_email').val()} );
if (after_id != "") {
aoData.push( {"name": "after_id", "value": after_id} );
}
if ($('#search_id_product').val()) {
aoData.push( {"name": "product_id", "value": $('#search_id_product').val()} );
}
$.ajax({
"dataType": 'json',
"type": "GET",
"url": url_data_source,
"data": aoData,
"success": function(result) {
var message_error = result.message_error
if (message_error) {
$('#datatable_processing').css("visibility","hidden");
swal({ title: message_error, type: "error"});
} else if (result.status == "OK") {
result.data = formatingDatatable(result.data)
fnCallback(result)
lastQuery = aoData;
} else {
$('#datatable_processing').css("visibility","hidden");
swal({ title: "Tidak ada hasil", type: "info"});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
swal({ title: manager.getAjaxError(XMLHttpRequest), type: "error"});
$('#datatable_processing').css("visibility","hidden");
$('.load__overlay').hide();
},
beforeSend: function() {
$('#datatable_processing').css("visibility","visible");
$('.load__overlay').show();
},
complete: function() {
$('#datatable_processing').css("visibility","hidden");
$('.load__overlay').hide();
}
});
}
});
}
function redraw() {
$("#datatable").dataTable().fnClearTable();
}
function formatingDatatable(events) {
var result = [];
var uri_next;
$.each(events.location_products, function(i, productlocation) {
result.push({
id: productlocation.id,
location_id: productlocation.location_id,
product_id: productlocation.product_id,
status_str: productlocation.status_str,
actions:'<button class="btn btn-primary waves-effect waves-light m-b-5 btn-sm m-r-5 btn-sm detail-productlocation" data-target="#modal-event-productlocation-detail" data-toggle="modal" data-id="' + productlocation.id + '" product-id="' + productlocation.product_id + '" location-id="' + productlocation.location_id + '" status-str="' + productlocation.status_str + '"><i class="glyphicon glyphicon-list"></i> Details</button>'
});
})
$("#after_id_url").val(events.page.uri_next)
uri_next = events.page.uri_next
result.after_id_url = uri_next
return result
}
function initFilter() {
$("#filter-form").submit(function() {
url_data_source = '/event/productlocation/ajax?action=data_source';
if(oTable == null){
initDataSource("");
} else {
oTable.fnDraw();
}
return false;
});
}
$('#datatable_paginate').on('click', '#datatable_next', function() {
initDataSource("");
})
$('#datatable').on('click', '.detail-productlocation', function() {
$('.load__overlay').show();
$("#modal-event-productlocation-detail").remove();
$(this).removeAttr("data-target", "#modal-event-productlocation-detail");
$(this).removeAttr("data-toggle", "modal");
//var id = $(this).attr("data-id");
var dt = {
"id": $(this).attr("data-id"),
"product_id": $(this).attr("product-id"),
"location_id": $(this).attr("location-id"),
"status": $(this).attr("status-str"),
}
$.ajax({
"url": '/event/productlocation/ajax?action=show_dialog_details',
"type": 'GET',
"data": dt,
success: function (result) {
$('.load__overlay').hide();
$("body").append(result);
$(this).attr("data-target", "#modal-event-productlocation-detail");
$(this).attr("data-toggle", "modal");
$('#modal-event-productlocation-detail').modal('show');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('.load__overlay').hide();
swal({ title: manager.getAjaxError(XMLHttpRequest), type: "error", });
},
});
});
$(document).ready(function() {
//initDate();
initFilter();
//initCategoryList();
var after_id = "";
initDataSource(after_id);
});
})(window);
event-productlocation-update.js
function sendProductLocationData() {
var jsonData = {};
var formFields = $(":input");
jQuery.each(formFields, function(i, field) { //Accessing all the element of form and get Key and Value
var key = field.name; //Keyname of each Field
var elementid = field.id; //Id of each Field
elementid = "#" + elementid;
var value = $(elementid).val();
jsonData[key] = parseInt(value);
if (key == "status") {
if ($("#event_checkbox_status").is(':checked') == true) {
jsonData.status = 1;
} else {
jsonData.status = 0;
}
}
});
productlocationdetail = JSON.stringify(jsonData); //Creating json Object
$.ajax({
url: '/update/product/productlocation',
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: productlocationdetail,
"success": function(result) {
var message_error = result.message_error
if (message_error) {
$('#modal-event-productlocation-detail').css("visibility", "hidden")
swal({
title: message_error,
type: "error"
});
$('.modal-backdrop').remove();
} else {
$('#modal-event-productlocation-detail').css("visibility", "hidden")
swal({
title: "Product Location Updated Successfully",
type: "info"
});
$('.modal-backdrop').remove();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
swal({
title: manager.getAjaxError(XMLHttpRequest),
type: "error"
});
$('#modal-event-productlocation-detail').css("visibility", "hidden")
$('.modal-backdrop').remove();
$('.load__overlay').hide();
},
beforeSend: function() {
$('#modal-event-productlocation-detail').css("visibility", "visible")
$('.modal-backdrop').remove();
},
complete: function() {
swal({
title: "Product Location Updated Successfully",
type: "info"
});
$('#modal-event-productlocation-detail').css("visibility", "hidden")
$('.modal-backdrop').remove();
$('.load__overlay').hide();
}
});
}
There are a few way you could handle this.
One way you could handle this is to store the item/s in a variable in a jSON array.
When get confirmation back from the server that that the the update was successful you could then create function to update the dataTable with with this function.
function updateDataTable(dataTableObj,jsonArray)
/*
Clears and populates the dataTable with JSON array
*/
dataTableObj.clear();
jsonArray.forEach(function(row){
dataTableObj.row.add(row);
});
dataTableObj.draw();
}
The other way you could update the table is to create a route on your server that sends the jsonArray but this requires an additional request to the server.
Note: If you use the Ajax call be sure to invoke the function inside the the ajax callback function

Load row information from DataTable created with AJAX

I have the next form.
This table is created with an AJAX call, here is the code:
$.ajax({
type: 'POST',
url: urlServer + "../webserviceURL", //URL del Web Service
data: '{"us":"' + sessionStorage.Usuario + '"}',
dataType: 'json',
contentType: 'application/json',
timeout: 600000,
error: function (xhr) {
lineas += '<tr><th colspan="8" class="text-center">No se encontraron registros de los cursos.</th></tr>';
$('#Tabla6').html(lineas);
bootbox.alert("No se pudo cargar los cursos.");
},
success: function (data) {
$('#Tabla6').dataTable({
"aaData": JSON.parse(data.d),
"aoColumns": [{
"mDataProp": "Id"
}, {
"mDataProp": "Nombre"
}, {
"mDataProp": "ContraseƱa"
}, {
"mDataProp": "Tipo"
}, {
"mDataProp": "Correo"
}, {
"mData": "",
"bSortable": false,
"mRender": function (oObj) {
return '<span class="btn btn-success fa fa-edit"></span>';
}
}]
});
}
});
Works fine but I want to load the row information when user click the "pencil button" and I dont know exactly how to do this. The only thing I need is load the row information to this method:
$('#Tabla6').on('click', '.glyphicon-edit', function () {
var id = $(this).attr('data-id');
editarDatosUsu(id);
});
editarDatosUsu Method:
function editarDatosUsu(id) {
if ($('#U' + id).length) {
var id = $('#U' + id).attr('data-id');
$('#IdUs').val(id);
var rev = $('#U' + id + '-1').html();
var pass = $('#U' + id + '-2').html();
var tipo = $('#U' + id + '-3').html();
var mail = $('#U' + id + '-4').html();
$('#user').val(rev);
$('#pass').val(pass);
$('#tipo').val(tipo);
$('#mail').val(mail);
}
Here's what I do:
$("#dashboardTable").on( 'click', '.approveLink', function () {
var tableRow = table.row( $(this).parents('tr') );
var row = $(this).parents('tr');
approveDashboard(tableRow.data().id, row);
} );
(where table is the datatable)

javascript function not call in document.ready

I have two functions that make two combobox with jqwidgets libraries. two functions are mostly like each other. I call them in $(document).ready(function (), but first function is work well and the second not even call. I put the codes those in one function, but the second part never run.
function f1() {
var url2 = "/autosuggest/JsonOrigins.aspx";
var source2 = {
datatype: "json",
datafields: [{
name: 'id'
}, {
name: 'name'
}],
url: url2,
async: false
};
var dataAdapter2 = new $.jqx.dataAdapter(source2);
// Create a jqxComboBox
$("#originsjqxWidget").jqxComboBox({
source: dataAdapter2,
multiSelect: true,
displayMember: "name",
valueMember: "id",
width: 145
});
$("#arrow").jqxButton({});
$("#arrow").click(function () {
$("#originsjqxWidget").jqxComboBox({
showArrow: false
});
});
$("#originsjqxWidget").on('change', function (event) {
var items = $("#originsjqxWidget").jqxComboBox('getSelectedItems');
var selectedItems = "Selected Items: ";
$.each(items, function (index) {
selectedItems += this.label;
if (items.length - 1 != index) {
selectedItems += ", ";
}
});
$("#log").text(selectedItems);
});
};
function f2() {
var url = "/autosuggest/JsonTag.aspx";
var source = {
datatype: "json",
datafields: [{
name: 'id'
}, {
name: 'name'
}],
url: url,
async: false
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#categoriesjqxWidget").jqxComboBox({
source: dataAdapter,
multiSelect: true,
displayMember: "name",
valueMember: "id",
width: 145
});
$("#arrow").jqxButton({});
$("#arrow").click(function () {
$("#jqxComboBox").jqxComboBox({
showArrow: false
});
});
$("#categoriesjqxWidget").on('change', function (event) {
var items = $("#categoriesjqxWidget").jqxComboBox('getSelectedItems');
var selectedItems = "Selected Items: ";
$.each(items, function (index) {
selectedItems += this.label;
if (items.length - 1 != index) {
selectedItems += ", ";
}
});
$("#log").text(selectedItems);
});
}
$(document).ready(function () {
f1();
f2();
});
Remove the ; after your first function.
try this
var source2 = {
datatype: "json";
datafields: [{
name: 'id'
}, {
name: 'name'
}],
url: url2,
async: false
};
I think you have an extra ; at the end of function f1
function f1(){
...
if (items.length - 1 != index) {
selectedItems += ", ";
}
});
$("#log").text(selectedItems);
});
};

jqgrid addrowdata after calling ajax

I have question regarding adding another rowdata at the end of my jqgrid. What I wanted to do is that everytime I do a simple search on a particular transaction, and display it on my jqgrid, i want to have another row at the end which have my total computations. Below is my complete jqgrid code:.
$("#tblSupplier").jqGrid({
url: '',
datatype: 'local',
jsonReader : {
root: function(obj) {
var root = [];
if ('error' in obj)
{
showMessage(obj.error['class'] + ' error: ' + obj['error']['msg']);
}
else
{
var totalBdFt = '';
var bdft=0;
var amt=0;
var totalAmount = '';
$.each(obj['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
var row = {};
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = obj['result']['main']['metadata']['fields'][columnIndex].name;
row[fldName] = rowArrayValue;
if (fldName == 'transaction_date'){
$('#tallyDate').val(rowArrayValue);
}
if (fldName == 'supplier_name'){
$('#supplierName').val(rowArrayValue);
}
if (fldName == 'board_foot'){
bdft = parseFloat(bdft) + parseFloat(rowArrayValue);
}
if (fldName == 'total_amount'){
amt = parseFloat(amt) + parseFloat(rowArrayValue);
}
});
root[rowIndex] = row;
$('#totalBdft').val(parseFloat(bdft));
$('#totalAmt').val(parseFloat(amt));
});
};
return root;
},
page: "result.main.page",
total: "result.main.pageCount",
records: "result.main.rows",
repeatitems: false,
id: "0"
},
serializeGridData: function(postData) {
var jsonParams = {
'SessionID': $.cookie("SessionID"),
'dataType': 'data',
'simple_search_value':trim($("#searchSupAny").val()),
'recordLimit': postData.rows,
'recordOffset': postData.rows * (postData.page - 1),
'rowDataAsObjects': false,
'queryRowCount': true,
'sort_fields': postData.sidx
};
return 'json=' + JSON.stringify(jsonParams);
},
loadError: function(xhr, msg, e) {
showMessage('HTTP error: ' + JSON.stringify(msg) + '.');
},
colNames:['Transaction Num', 'Wood Classification', 'Specie', 'Total Board Foot', 'Price', 'Total Amount'],
colModel:[
{name:'transaction_num'},
{name:'wood_classification_desc'},
{name:'wood_specie_desc'},
{name:'board_foot'},
{name:'price'},
{name:'total_amount'}
],
viewrecords: true,
sortname: 'transaction_num',
sortorder: 'desc',
loadonce:false,
height:'100%',
caption: "sample summary"
});
var newRowData = [{ "wood_classification_desc": 'total should b here', "wood_specie-desc": "total bdft here", "total_amount": "total amount here"}];
$("#tblSupplier").addRowData('transaction_num',newRowData);
})
my newRowData displays only on load, but after I do a simple search, it will also gone. But my jqgrid with ajax data working good. So how should I do it to maintain my additional row everytime I call ajax?

Categories

Resources