Angular 6 datatable serverside ajax request not working - ajax

I am using angular datatable(1.10.19).
ref this for server side angular way
I have written web api in c# to get the data in desired format.
With following dtoptions, server side is working fine.
dtOptions = {
pagingType: 'full_numbers',
pageLength: 10,
processing: true,
serverSide: true,
orderCellsTop: true,
ajax: (dataTablesParameters: any, callback) => {
this.mainpageservice.GetPaginatedData(this.menuID, this.UserName, dataTablesParameters)
.subscribe(resp => {
this.Module = resp.data;
console.log('serverside', this.Module);
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: [],
});
});
},
Now, I want to display multiple tables that too using serverside angular way datatable. so to achieve this, I am using: for multiple datatables
as documented, I have created one function which is returning Datatable settings. But here ajax call is not working.
Can anyone suggest where I am doing wrong?.
private buildDtOptions(menu: number, Username: string): DataTables.Settings {
alert('call');
return {
pagingType: 'full_numbers',
pageLength: 10,
processing: true,
serverSide: true,
orderCellsTop: true,
ajax: (dataTablesParameters: any, callback) => {
console.log(dataTablesParameters);
this.mainpageservice.GetPaginatedData(menu, Username, dataTablesParameters).subscribe(resp => {
this.Module = resp.data;
console.log('serverside', this.Module);
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: [],
});
});
}
};
}

Not sure if you ran into the same issue that I did or not, but when I was moving to the "Server side the Angular way" from the "Angular Way", I forgot to remove the dtTrigger reference from the markup. Once I removed [dtTrigger]="dtTrigger" from the table tag all was good in my world.

Related

retrieve data for grid/chart from httpwebrequest call to url

I am trying to get a grid filled with the json response I would receive when making a httpwebrequest call to a url endpoint which requires authentication. The data will be in json form:
{
"data": [
{
"value": "(\"Samsung Health\")",
"tag": "ME"
},
{
"value": "(\"Samsung Galaxy Tab\")",
"tag": "HIM"
},
{
"value": "(\"Amazon fire\")",
"tag": "ME"
}
]
}
I am not sure how to even start and whether to use Ext.Ajax.Request or some type of call from code behind. I am using vb.net in code behind. Any suggestions appreciated. Sample code for ajax call;
function getMembers() {
var parameters = {
node: dynamicNodeId
}
Ext.Ajax.Request({
url: 'https://data.json',
method: 'GET',
jsonData: Ext.encode(parameters),
success: function (response, opts) {
alert('I WORKED!');
//decode json string
var responseData = Ext.decode(response.responseText);
//Load store from here
memberStore.loadData(responseData);
},
failure: function (response, opts) {
alert('I DID NOT WORK!');
}
});
}
The grid formation:
var grid = Ext.create('Ext.grid.Panel', {
store: store,
stateful: true,
stateId: 'stateGrid',
columns: [
{
text: 'Query',
flex: 1,
sortable: false,
dataIndex: 'query'
},
{
text: 'Last Updated',
width: 85,
sortable: true,
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
dataIndex: 'lastChange'
},
Here query would be the value from the json response and lastChange the current datetime. I tried the proxy request call and realized that since I am calling an endpoint on a different domain I needed to use jsonp.
var myStore = Ext.create('Ext.data.Store', {
model: 'User',
proxy: {
type: 'jsonp',
extraParams: {
login: 'username',
password: 'password'
},
url: 'https://api.data/rules.json',
reader: {
type: 'json',
root: 'rules'
},
callbackParam: 'callback'
},
autoLoad: true
});
I might have to just figure out some other way to do by making sure all the data I needed is called to a database by some other function.
The best approach for your situation would be to create store that is configured with a remote proxy. See the example at the top of this documentation page: http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.Store
The remote proxy will take care of the AJAX request to retrieve the data, and the store will automatically manage casting the data results to Ext.data.Model instances. Once the store is loaded with data, the grid to which the store is bound will also automatically handle rendering the data that has been populated into the store.

SharePoint 2013 and Kendo Grid cross domain call issues

I am having a small issue that I just can't seem to figure out. I am trying to make a simple SharePoint 2013 demo app that gets a few fields from a list on the parent site and binds to a kendo grid.
Due to the new nature of SP2013, app's get created in their own local site which makes these calls cross domain. When I make the call, no data is pulled back. When I compare a working call vs the call being made by the app, I can see that a cookie is not present in the call that is failing (which is why no data is being pulled back). If anyone could offer any hints or suggestions on things to try, I would appreciate it.
The List I am trying to call is called KendoGridList and I am trying to pull back the first and last name and bind to the grid. Below is my code:
EDIT: After looking into the code a little deeper, it looks like a cookie is not getting passed in the call to the service. If I take the cookie from a normal rest call to the service which works and add it to the composer in fiddler the call goes through and returns data.
$(document).ready(function () {
$("#grid").empty();
var siteUrl = "site url placed here";
var url = siteUrl + "/_vti_bin/Listdata.svc/KendoGridList/?$select=FirstName,LastName";
grid = $("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
url: url,
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json;odata=verbose");
}
}
},
schema: {
type: "json",
model: {
fields: {
FirstName: "FirstName",
LastName: "LastName"
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
change: function (e) { // data load completed for grid
},
},
filterable: false,
sortable: true,
pageable: true,
scrollable: false,
//groupable: true,
columns: [{
field: "FirstName",
title: "First Name",
width: 50
}, {
field: "LastName",
title: "Last Name",
width: 50
}
]
});
});
I've also tried using:
read: {
url: url,
type: "GET",
dataType: "json",
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose"
}
},
If you are using a provider-hosted app you should try using the SP cross-domain library. I think your best bet is to retrieve the data using the library and then bind the resulting info to the grid.
http://blogs.msdn.com/b/officeapps/archive/2012/11/29/solving-cross-domain-problems-in-apps-for-sharepoint.aspx

Kendo Grid does not update the grid with newly created id after creation

I am trying to build a very simple Kendo CRUD grid with a table that has only two columns: ID and Name. I have configured the grid with serverside pagination and serverside filtering.
Everything seems to function as expected but after the new record is created, the grid shows the new record but without the ID field. On creation, the request has ID null but I am sending the value of id and the full object after creation. In example grids, the grid is updated with new values. What do I need to change / add to ensure that the ID of the newly created record shows up in Grid as well?
Following is the JSP:
<script>
$(function() {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url:"http://localhost:8181/baseweb/countrylist",
dataType: "jsonp"
},
update: {
url: "http://localhost:8181/baseweb/countryupdate",
dataType: "jsonp"
},
destroy: {
url: "http://localhost:8181/baseweb/countrydelete",
dataType: "jsonp"
},
create: {
url: "http://localhost:8181/baseweb/countrycreate",
dataType: "jsonp"
},
parameterMap: function(data, operation) {
if (operation !== "read" && data.models) {
return {grid_options: kendo.stringify(data.models)};
}
return {grid_options: kendo.stringify(data)};
}
},
serverPaging: true,
serverFiltering: true,
pageSize: 10,
schema: {
data: "data",
total: "total",
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
filterable: true,
height: 400,
toolbar: ["create"],
columns: [
{ field: "id", title:"Identification"},
{ field: "name", title:"Country Name" },
{ command: ["edit", "destroy"], title: " ", width: "160px" }
],
editable: "popup"
});
});
</script>
Parameter Sent to the server on create:
_ 1380846899054
callback jQuery19108827040256333442_1380846899052
grid_options {"id":null,"name":"testing"}
Parameter sent back from server as response:
jQuery19108827040256333442_1380846899052([ {"id":"4028828f4180d64a014180e3bda20002","name":"testing"}])
I am expecting that the ID sent back by server should be displayed in the Grid. I have searched this forum, Kendo documentation and Google for an answer but I am unable to find a solution.
What am I missing?
Update with Solution:
Jack's answer provided the clue to finding the solution. I was making two mistakes:
a. The callback in Kendo Grid seems to expect the data back in a "data:" attribute. I was not naming the result set as "data:" in my response.
b. The callback also expects a JSONArray of objects in the data: attribute. I was sending a JSONObject since I was only creating one object.
After I changed the response to include data: attribute and JSONArray, it works perfectly.
The request parameter from the client looks like this:
_ 1386350196768
callback jQuery19101285024500179227_1386350196765
grid_options {"id":null,"name":"Ghana"}
The edited response looks like this:
jQuery19101285024500179227_1386350196765( {"data":[{"id":"2c9323ca42c8df630142c944450b0002","name":"Ghana"}]})
Hope it helps someone else as this is not clearly documented in the official documentation.
There is a nice clean way of doing this...
If your grid is created in script block:
dataSource: {
transport: {
read: {
url: "..."
},
create: {
url: "...",
type: "POST",
complete: function(e) {
$("#grid").data("kendoGrid").dataSource.read();
}
},
}...
OR in HTML
#(Html.Kendo().Grid<ViewModel>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Model(model =>
{
model.Id(i => i.Cde);
model.Field(i => i.Description).Editable(true);
})
.Read(read => read.Action("EditingInline_Read", "UserGroups"))
.Update(update => update.Action("EditingInline_Update", "UserGroups")).Read("EditingInline_Read", "UserGroups")
.Destroy(delete => delete.Action("EditingInline_Delete", "UserGroups"))
.Create(create => create.Action("EditingInline_Create", "UserGroups")).Read("EditingInline_Read", "UserGroups")
)
.Columns(columns =>
{
columns.Bound(s => s.Decription);
columns.Bound(s => s.enabled);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(200);
})
.Pageable()
.Sortable()
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single))
.ToolBar(toolbar => toolbar.Create()))
Check out the CRUD calls, more specific, Update and Create.
I've had the same problem and think I may have found the answer. If in the schema you define the object that holds the results, you must return the result of the created link in that same object. Example:
schema: {
data: "data",
total: "total", ....
}
Example MVC method:
public JsonResult CreateNewRow(RowModel rowModel)
{
// rowModel.id will be defaulted to 0
// save row to server and get new id back
var newId = SaveRowToServer(rowModel);
// set new id to model
rowModel.id = newId;
return Json(new {data= new[] {rowModel}});
}

FineUploader onSubmit not being called

Using FineUploader 3.8.2 to upload PDF files to S3, I am running into an interesting issue and not sure if perhaps I'm just using the wrong syntax or not understanding how the options should work for fineUploader. Here is my code...
var uploader = $('#fine-uploader-box').fineUploaderS3({
debug: true,
button: $('#choose-file-button'),
multiple: false,
autoUpload: false,
request: {
endpoint: '(no url yet because I need to know about the file before I can construct an S3 PUT url)'
},
callbacks: {
onSubmit: function(id, name){ // function to get real endpoint url goes here },
onSubmitted: function(id, name){ // or function to get real endpoint url goes here }
},
validation: {
allowedExtensions: ['pdf']
}
});
What I am trying to do is just get a function to run once my file has been added to the list but I am not seeing the onSubmit (or onSubmitted) firing.
My goal is to have that function do some ajax-y stuff and return some information in which I will use to facilitate the rest of the upload process including getting a specialized S3 PUT url from my server to send my upload to.
Any help would be greatly appreciated. Thanks.
It appears that you are using the syntax for the non-jQuery uploader, but you are using the jQuery uploader. Check out the below:
var uploader = $('#fine-uploader-box').fineUploaderS3({
debug: true,
button: $('#choose-file-button'),
multiple: false,
autoUpload: false,
request: {
endpoint: '(no url yet because I need to know about the file before I can construct an S3 PUT url)'
},
validation: {
allowedExtensions: ['pdf']
}
}).on('submit', function (event, fileId, fileName) {
alert("File id: "+fileId);
}).on('submitted', function (event, fileId, fileName) {
alert("File id: "+fileId);
});

ExtJS 4 rendering new grid based on a combobox selection

I have a grid which uses a remote store and remote pagination because I have too many records.The store for the main grid is:
Ext.define('ArD.store.RecordsListStore', {
extend: 'Ext.data.Store',
model: 'ArD.model.RecordsListModel',
autoLoad: true,
autoSync: true,
remoteSort: true,
remoteFilter: true,
pageSize: 15,
proxy: {
type: 'ajax',
actionMethods: 'POST',
api: {
read: g_settings.baseUrl + 'index.php/recordslist/getAll',
destroy: g_settings.baseUrl + 'index.php/recordslist/deleteRecord'
},
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount',
successProperty: 'success'
},
writer: {
root: 'data',
writeAllFields: true,
encode: true
}
}
});
then I populate my grid and and it's all fine. But the problem is that I have a combobox which looks like this:
{
xtype: 'combo',
id: 'records_list_form_id',
emptyText: 'Choose Form',
editable: false,
store: 'FilterRecordsByForm',
displayField: 'title',
valueField: 'id',
lastQuery: '',
triggerAction: 'all',
queryMode: 'remote',
typeAhead: false,
width: 200,
listeners: {
select: this._filterRecords
}
}
And when I select something from the combobox there's the function :
_filterRecords: function()
{
var recStore = Ext.getStore('RecordsListStore');
var a = Ext.getCmp('records_list_form_id').getValue( );
var rec = Ext.getStore('FilterRecordsByForm').getAt(a);
console.log(recStore);
},
mostly just trying some things but I can get the ID of the selected element from the combobox and that is where I am.
What I need is having the id to make a new query usign my AJAX api (PHP/SQL backend) and populate the grid with the info related with this id. In my case I have 1:M relations so when I pass the Id i expect M records which I want to render on the place of the old grid.
Thanks
Leron
Use filter() method. Provide information that you need to filter by and store object will automatically request updated info from the server (you already have remoteFilter configured).
Look at Ext.Ajax() to make an on-demand ajax call to the server-side to load up your data and then use Store.loadData() or something like that to re-populate the Grid.

Resources