Create ui-grid with async call - javascript

I am trying to create a ui-grid with some DDL filter (from get data). If I try with async: false, all works perfectly. This is the call:
var Documents = [];
var solutionSetColumn = {};
var solutionSetFilters = [];
LoadData = function () {
Documents = [];
$.ajax({
type: "POST", url: url,
success: function (data) {
Documents = data.d;
},
error: function (err) {
}
});
}
}
$.ajax({
type: "POST", url: url,
success: function (data) {
solutionSetColumn = { field: 'SolutionSet', displayName: 'Solution Set', width: 190, filter: { type: uiGridConstants.filter.SELECT, selectOptions: data.d } };
},
error: function (err) {
solutionSetColumn = { field: 'SolutionSet', displayName: 'Solution Set', width: 190 }
}
});
LoadData();
gridOptions = {
enableHorizontalScrollbar: 2,
enableVerticalScrollbar: 0,
enableFiltering: true,
data: Documents,
columnDefs: [
{ field: 'Name', displayName: 'Nome File', width: 200 },
solutionSetColumn
]
}
$scope.gridOptions = gridOptions;
});
How to get all async without gridOption error like colDef undefined? Obviously without the setTimeout! Thanks

You need to move your $scope.gridOptions (and the options definition) into the success path of your ajax call.

Related

Using the content of a variable returned by DataTables in another part of the script

How can I use the "DeviceID" in the "columns:" in another part of the script. I have tried all manner of things like re positioning some of the code but no matter what I do I can't get it to work.
I need to use the "DeviceID" as a variable in
"url: 'get_wayfinder_offline_status.php', data: { DeviceID: deviceid },"
Look at << USE THIS IN PART MARKED "HERE"
$(document).ready(function() {
var table = $('#WayFinderStatusTable').DataTable({
ordering: false,
paging: false,
searching: false,
bInfo: false,
responsive: true,
fixedHeader: true,
scrollX: false,
pageResize: true,
ajax: {
url: 'check_wayfinder_status.php',
dataSrc: ''
},
columns: [{
data: 'DisplayDescription',
"sWidth": "100%"
},
{
data: 'DeviceName',
"visible": false
},
{
data: 'MessageCount',
"visible": false
},
{
data: 'BoardOverride',
"visible": false
},
{
data: 'DeviceID',
"visible": false
}, // << USE THIS IN PART MAKED "HERE"
],
rowCallback: function(row, data, dataIndex) {
if (data.MessageCount == 2) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
} else if (data.BoardOverride == 1) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOverrideOn ');
$('#WayFinderStatusTable tbody').on('click', 'tr', function() {
var hotelid = "<?php echo $_SESSION['_amember_user']['hotelid'];?>";
var data = table.row(this).data();
var deviceid = data.DeviceID;
console.log("DEVICE ID", deviceid);
$.ajax({
url: 'get_wayfinder_override_status.php',
data: {
DeviceID: deviceid
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
console.log("BoardName", result);
$('#EditOverrideWayfinderRecordID').val(result[0]);
$('#EditOverrideWayfinderBoardName').val(result[1]);
var testimage = result[2];
console.log("TEST IMAGE", testimage);
$('#EditOverrideWayfinderImage').val(result[2]);
var imagepath = '../../../../conf/conf_images/override/' + hotelid + '/' + result[2];
$("#EditOverrideWayfinderLookUpCompanyImage").attr("src", imagepath);
$("#EditOverrideWayfinderImagePreview").attr("src", imagepath);
$('#EditOverrideWayfinderRoomFromDate').val(result[3]);
$('#EditOverrideWayfinderRoomFromTimeH').val(result[4]);
$('#EditOverrideWayfinderRoomFromTimeM').val(result[5]);
$('#EditOverrideWayfinderRoomToDate').val(result[6]);
$('#EditOverrideWayfinderRoomToTimeH').val(result[7]);
$('#EditOverrideWayfinderRoomToTimeM').val(result[8]);
$('#EditOverrideWayfinderPromotionName').val(result[9]);
$('#EditOverrideWayfinderHardwareID').val(result[10]);
$('#edit_wayfinder_override_data_modal').modal('show');
}
}
});
});
} else if (data.BoardOverride == "") {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOff');
}
},
});
$(document).on('click', '.WayFinderStatusTableOff', function(e) {
$('#wayfinder_override_data_modal').modal('show');
});
$(document).on('click', '.WayFinderStatusTableOn', function(e) {
console.log("OFFLINE CLICKED");
$.ajax({
url: 'get_wayfinder_offline_status.php',
data: {
DeviceID: deviceid //<<HERE
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
// DO SOMETHING
}
}
});
$('#offline_data_modal').modal('show');
});
setInterval(function() {
$('#WayFinderStatusTable').DataTable().ajax.reload();
}, 30000);
});
Based on structure of your datatables and column, clicked on a row the deviceId is find by using the method table.row( this ).data(); and next find the right index of the data.
$('#WayFinderStatusTable').on('click', 'tr', function () {
const data = table.row( this ).data();
const deviceId = data[4];
alert(deviceId + ' -> deviceid');
});

Data is not populated in the grid after the ajax call

I am trying to use js grid for my application. I am trying to populate the grid after ajax request but it do not seem to work as expected.
I am trying with SQL Server as back end and web application is asp.net MVC
This is my code in the html
var table;
var result;
var $j = jQuery.noConflict();
$j(document).ready(function () {
table = $j('#grid').jsGrid({
height: "60%",
width: "50%",
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
controller: {
loadData: function (filter) {
var d = $j.Deferred();
$j.ajax({
type: "POST",
contentType: "application/json",
url: "#Url.Action("LoadData", "User")",
datatype: "json",
data: filter
#*success: function (data) {
result = data.data;
console.log("result", result);
d.resolve(result)
},
error: function (data) {
window.location.href = '#Url.Action("Error", "Audit")';
}*#
}).done(function (data) {
console.log("response", data);
console.log("data.data", data.data);
d.resolve(data)
});
return d.promise();
},
fields: [
{ name: "LastName", type: "text"},
{ name: "FirstName", type: "text"},
{ name: "Email", type: "email"},
{ name: "PhoneNumber", type: "number"},
{ type: "control" }
]
}
});
});
In Controller I return
''return Json(new { data }, JsonRequestBehavior.AllowGet);''
I expect the json data to bind in the div. But it did not ? Thanks
Ok, so I've had this problem recently.
First off, change your "height" to px, auto, or get rid of it entirely. It's not doing what you think it's doing.
Next, since you have paging, you need to return your data in the following format:
{
data: [{your list here}],
itemsCount: {int}
}
It's barely in the documentation, as it's inline and not very obvious. (Bolding mine.)
loadData is a function returning an array of data or jQuery promise that will be resolved with an array of data (when pageLoading is true instead of object the structure { data: [items], itemsCount: [total items count] } should be returned). Accepts filter parameter including current filter options and paging parameters when
http://js-grid.com/docs/#controller

how to reload dataTable

I want to empty the table before processing. It's showing error.
Cannot read property 'aDataSort' of undefined.
i am calling like this: $('#fulltalktimepdata').dataTable().empty();
$.ajax({
type: "POST",
url: "/recharge_plan/",
data: {
'phone_no': phone_no
},
dataType: "json",
success: function(msg1) {
var fulltalktime_jsonString = msg1.fulltalktime_response_data;
var fulltalktime_temp_data = JSON.parse(fulltalktime_jsonString);
var fulltalktime_array_of_arrays = [];
$.each(fulltalktime_temp_data.data["FTT"], function(i, dataElem) {
fulltalktime_array_of_arrays.push([dataElem.amount, dataElem.detail, dataElem.validity, dataElem.talktime]);
});
console.log(fulltalktime_array_of_arrays);
$('#fulltalktimepdata').dataTable().empty();
$('#fulltalktimepdata').DataTable({
data: fulltalktime_array_of_arrays,
columns: [{
title: "AMOUNT"
},
{
title: "DETAIL"
},
{
title: "VALIDITY"
},
{
title: "TALKTIME"
}
]
});
}
});
Cannot read property 'aDataSort' of undefined

csrf token set as post parameter while deleting action in Jtable (Jquery )

Hi i'm trying to add csrf token in post while deleting record in jtable its not working but listAction & updateAction is working fine.
My Code snippets :-
$(document).ready(function () {
$('#main-content').jtable({
title: ' Data',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
actions: {
listAction:"${pageContext.request.contextPath}/mycontroller/all" ,
// createAction:"${pageContext.request.contextPath}/mycontroller/create",
updateAction:"${pageContext.request.contextPath}/mycontroller/edit",
deleteAction:"${pageContext.request.contextPath}/mycontroller/delete"
},
fields: {
code: {
title:'Code',
width: '25%',
key: true,
edit:true,
input: function (data) {
if (data.value) {
return '<input type="text" readonly class="jtable-input-readonly" name="code" value="' + data.value + '"/>';
}
},
},
name: {
title: 'Name',
width: '25%',
create:true,
edit:true
},
craetedTs: {
title: 'Created',
width: '25%',
edit:false
},
modifiedTs: {
title: 'mdate',
width: '25%',
edit:true,
input: function (data) {
if (data.value) {
mdate='';
var date = new Date();
var options = {
year: "numeric", month: "2-digit",
day: "2-digit", hour: "2-digit", minute: "2-digit" ,second:"2-digit"
};
today=date.toLocaleTimeString("en-us", options);
today=today.replace(',', '');
return '<input type="text" readonly class="jtable-input-readonly" name="modifiedTs" value="' + today + '"/>';
}
}
},
_csrf: {
visibility: 'hidden',
edit:true,
input: function (data) {
return '<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />';
}
}
}
});
$('#main-content').jtable('load',{'${_csrf.parameterName}' : '${_csrf.token}'});
//Delete selected
$('#DeactiveID').button().click(function () {
var $selectedRows = $('#main-content').jtable('selectedRows');
$('#main-content').jtable('deleteRows', $selectedRows);
});
});
Even i tried for deleting code bellow:-
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
data: '${_csrf.parameterName}' + "=" +'${_csrf.token}' ,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
But when i checked delete action url the entire method was reflecting
Add meta elements to the page you are invoking the ajax method from
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
And make this change to your deleteAction
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
beforeSend: function (request)
{
request.setRequestHeader(header, token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
If somebody is still wondering, Lalit got me going in the right direction, but my final solution is this:
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
This solves the issue with passing csrf, or any additional data, for that matter, in jTable AJAX delete call. As for the other cases. Putting this right after you include the jTable js foxes the initial load:
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
And then there is this hidden field to add to the field list:
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
Here is my code as a full example:
<!-- Include jTable script file. -->
<script src="{{site.uri.public}}/jtable/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
var csrf_token = $('meta[name=csrf_token]').attr("content");
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var csrf_token = $('meta[name=csrf_token]').attr("content");
$("#PrizesTableContainer").jtable({
title: 'Prizes',
actions: {
listAction: 'prizes/get',
createAction: 'prizes/create',
updateAction: 'prizes/update',
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
},
fields: {
id: {
key: true,
list: false
},
machine_name: {
title: 'Machine name',
width: '10%'
},
reel1: {
title: 'Reel1',
width: '15%'
},
reel2: {
title: 'Reel2',
width: '15%'
},
reel3: {
title: 'Reel3',
width: '15%'
},
payout_credits: {
title: 'Payout credits',
width: '15%'
},
payout_winnings: {
title: 'Payout winnings',
width: '15%'
},
probability: {
title: 'Probability',
width: '15%'
},
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
}
});
$("#PrizesTableContainer").jtable('load');
});
</script>

Select2 TypeError: data.results is undefined

Am trying to use Select2 to load remote data using ajax / json but i keep getting an error as:
TypeError: data.results is undefined
My code is :
$('#tags').select2({
ajax: {
url: 'http://localhost:8090/getallusers',
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
return data;
}
}
});
I really Don’t Understand the Problem !
Select2 needs the results as a collection of objects with id: and text: attributes.
Like:
[{ 'id': 1, 'text': 'Demo' }, { 'id': 2, 'text': 'Demo 2'}]
Try, to reformat you response like:
$('#tags').select2({
ajax: {
url: 'http://localhost:8090/getallusers',
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.first_name + " " + item.last_name
});
});
return {
results: myResults
};
}
}
});

Categories