I'm trying to use jsGrid in my MVC project as the client would like inline editing and filtering.
However, I cannot get it to load my JSON source into the table.
My js to load the table looks like so:
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "RICInstrumentCode/GetData",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
return $.ajax({
type: "CREATE",
url: "/api/RICInsrumentCodeTable",
data: item,
dataType: "json"
});
},
updateItem: function (item) {
return $.ajax({
type: "UPDATE",
url: "/api/RICInsrumentCodeTable/" + item.ID,
data: item,
dataType: "json"
});
},
deleteItem: $.noop
//deleteItem: function (item) {
// return $.ajax({
// type: "DELETE",
// url: "/api/data/" + item.ID,
// dataType: "json"
// });
//}
},
fields: [
{ name: "Code", type: "text", title: "RIC Instrument Code", width: 150 },
{ name: "Descr", type: "text", title:"RIC Instrument Code Description", width: 200 },
{ name: "RICInstrumentGroupId", type: "select", title: "RIC Instrument Group", items: countries, valueField: "Id", textField: "Name" },
{ name: "Active", type: "checkbox", title: "Is Active", sorting: true },
{ type: "control" }
]
});
});
The loadData is what I've been working on.
and the JSON the is returned from get data looks like so:
[{"Id":1,"Code":"test1","Descr":"first code test","RICInstrumentGroupId":2,"Active":true},{"Id":2,"Code":"APP","Descr":"Apples and bananas","RICInstrumentGroupId":4,"Active":true},{"Id":3,"Code":"1","Descr":"1","RICInstrumentGroupId":1,"Active":true},{"Id":4,"Code":"3","Descr":"3","RICInstrumentGroupId":3,"Active":false}]
So far I have confirmed that the ajax is firing, changed my array titles to match those of the call, and ensured the return is in valid JSON, what else can I do? Why isn't this working?
I was being stupid,
The bit that sets the table height was set to a 100% in a div that had no height, this was causing the table body to render with a height of 0px, changing the height property to auto fixed it because the data was there all along.
Thanks for the advice though!
I don't know if it is required, but when I look on demo examples (OData Service).
The grid loadData function looks bit different than yours.
loadData: function() {
var d = $.Deferred();
$.ajax({
url: "http://services.odata.org/V3/(S(3mnweai3qldmghnzfshavfok))/OData/OData.svc/Products",
dataType: "json"
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
is accept promise rather than ajax function. so that my be the problem
Demo here: http://js-grid.com/demos/
Related
I am trying to populate one of the columns using select box in jqgrid. Below is the code.
$(document).ready(function(){
$("#grid").jqGrid({
url: "./info",
datatype: "json",
mtype: "GET",
ajaxSelectOptions:{
type: "GET",
dataType: "json",
success: function (result) {
console.log(result);
}
},
colNames: ["DeptId", "DeptName", "StuId", "StuName", "StuDoj"],
colModel: [
{ name: "deptId", hidden:true },
{ name:"deptName", width:90, editable:true, edittype:'select', formatter:'select', editoptions:{
dataUrl:'./getDepts',
buildSelect: function(res){
console.log(res);
var s='<select id="dept" name="dept">'
$.each(res,function(idx,obj){
$('#dept')
.append($('<option>', { value : obj.deptId })
.text(obj.deptName));
});
return s+"</select>";
}
}},
{ name: "studentId", hidden:true },
{ name: "studentName", width: 80,editable:true },
{ name: "studentDoj",width: 90,editable:true }
],
pager: "#pager",
rowNum: 5,
rowList: [5, 10, 20],
sortname: "empId",
sortorder: "asc",
sortable:true,
viewrecords: true,
gridview: true,
caption: "MyGrid",
jsonReader: {
repeatitems: false,
id: "empId",
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}
});
$("#grid").jqGrid('navGrid','#pager',{add:false,view:true,search:true});
})
In the editOptions for colModel 'deptName' the dataUrl is not called to populate the select box. The jqgrid is populated using /info resturl which fetches the deptName for a particular student. I want the deptName to be of type select box and its value should be same as deptName fetched using info rest url
It should be called, but your data will be newer filled, since you overwrite the success function in ajaxSelectOptions.
In order to get response, please comment the success function or remove it
$("#grid").jqGrid({
url: "./info",
datatype: "json",
mtype: "GET",
ajaxSelectOptions:{
type: "GET",
dataType: "json"
},
....
});
UPDATE: With small changes your code is working fine. Here is a link to your code
Note that the formatter does not have option dataUrl. It is only available in in editing.
I am getting JSON data via AJAX and my data are in a result object. The fields of which can be accessed as in success: function(result)
result.map.count[0].name
result.map.count[0].count
I would like to show name and count as two columns of my datatable.
My ajax request is written as
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
I am able to get data as "result" here
result.map.count[0].name
result.map.count[0].count
}
});
},
columns: []
})
what should I put in columns[] to show these fields?
columns: []
In your datatable configuration,add the following
data: [[result.map.count.name,result.map.count.count]], // make it as array of values
columns: [
{
"sClass": "center",
"name": "Name"
},
{
"sClass": "center",
"name": "Count"
},
]
Please check here for more details
https://datatables.net/examples/data_sources/js_array.html
I've found my answer.
I need to write a callback function that returns the data (array) which is found from my object.
Code:
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
var dataToUse = {};
dataToUse.data = result.map.count;
callback(dataToUse);
}
});
},
columns: [
"data": "name",
"data": "count"
]
})
}
Please try this.
table = $('#_table').dataTable({
searching: false,
paging: true,
ajax: function (data, callback, settings) {
$.ajax({
type: "post",
url: '/test/getvalues',
dataType: "json",
success: function (result) {
callback(result.map.count);
}
});
},
// Columns
columns: [{
title: "Name",
name: "name",
}, {
title: "Count",
name: "count"
}]
});
I have a mix of Select2JS and Datatables and here is the code involved in the issue:
$(function() {
var form_id = $('#form_id'),
form_results = $('#form_results');
form_results.DataTable();
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'json',
url: '/ajax/forms/get/',
data: JSON.stringify({
form_id: null,
show_archived: !!$('#show_archived').is(':checked'),
get_first: false,
format: 'select2',
}),
cache: false,
success: function(data) {
form_id.removeAttr('disabled');
form_id.select2({
data: data,
closeOnSelect: true,
matcher,
sorter,
}).on('select2:select', function(e) {
var selected_element = $(e.currentTarget);
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'json',
url: '/ajax/manage_forms/getFormData/',
data: JSON.stringify({
form_id: selected_element.val(),
get_first: true,
}),
cache: false,
success: function(response) {
form_results.DataTable({
data: response.data,
retrieve: true,
stateSave: true,
responsive: true,
columnDefs: [
{
className: 'select-checkbox',
orderable: false,
searchable: false,
targets: 0,
},
],
select: {
style: 'multiple',
selector: 'td:first-child',
},
});
},
error: function(xhr, ajaxOptions, thrownError) {
console.error(xhr.responseText);
},
});
});
},
error: function(xhr, ajaxOptions, thrownError) {
console.error(xhr.responseText);
},
});
});
On the PHP side there is a function building the data and send it back to the browser:
public function getFormData()
{
$inputJSON = file_get_contents('php://input');
$outputJSON = json_decode($inputJSON, true);
$arguments = array(
'Id' => $outputJSON['form_id'],
'FormName' => null,
'FormFileName' => null,
'FormTypeId' => 1
);
$form = $this->forms_model->get($arguments, $outputJSON['get_first'], self::$folders);
$result[] = array(
'',
'DT_RowId' => $form->Id,
$form->FormName,
$form->FaxNumber,
end(explode('/', $form->form_filepath))
);
return $this->output->set_content_type('application/json')->set_output(json_encode(array('data' => $result)));
}
The result from the above function looks like:
{
"data" : [
{
"0" : "",
"DT_RowId" : 3387,
"1" : "form",
"2" : "8772399284",
"3" : "form1.pdf"
}
]
}
For some reason the table is showing all the time "No data available in table" and I can't find where is the issue, can any find out what is wrong in my code?
I have spent the last two hours trying to figure this out but I can't.
Updates:
#charlietfl: the following didn't work at first complaining about the k not being defined so I modified a little bit however it didn't do the trick
response.data.map(function(k, o) {
return Object.keys(k).map(function(k) { return o[k];});
});
#CFP Support: your solution is not working either for some reason the table doesn't get updated with data.
In both cases I am not getting any Javascript error or nothing weird in the console it just does not work.
You need to add the "columns" and define them.
...stuff...
columnDefs: [
{
className: 'select-checkbox',
orderable: false,
searchable: false,
targets: 0,
},
],
columns: [
{data: "0"},
{data: "DT_RowId"},
{data: "1"},
{data: "2"},
{data: "3"}
], ....etc...
This tells the table what column to match with the incoming data (so you will need a table with 5 columns in the HTML - or build it with JS {not sure what you are using, but if you need help...}
This should get you past the immediate issue though.
EDIT: JSFiddle - https://jsfiddle.net/CFPSupport/5utwh4v3/6/
EDIT2: I see the issue - you are initializing then wanting to put more data.... OK.....
You should get the data IN the datatable init, not init+AJAX.... https://datatables.net/reference/option/ajax
I'm trying to populate a kendo grid with data retrieved via ajax. Here is the ajax:
var model = #Html.Raw(Json.Serialize(Model));
$(document).ready(function () {
$.ajax({
url: "/Utilities/Report/Run",
data: JSON.stringify(model),
contentType: "application/json",
type: "POST",
success: function(result) {
var ds = new kendo.data.DataSource({
data: result
});
alert(result);
$("#grid").data("kendoGrid").setDataSource(ds);
},
error: function(result) {
options.error(result);
}
});
$("#grid").kendoGrid({
toolbar: ["excel", "pdf"],
excel: {
fileName: "test"
},
pdf: {
fileName: "test"
},
});
});
At the alert(result) this is what the data looks like:
[
{"TEST":"one"},
{"TEST":"two"},
{"TEST":"three"}
]
The ajax call appears to be working and the data looks good to me, but the kendo grid is not updating, it remains blank. I also do not get any error. I've tried placing the kendoGrid inside the ajax success function with the same result. I've tried using transport and read in the DataSource to retrieve the data but that kept giving me an error: n.slice is not a function. However, others seemed to think that was because there was no schema defined. Due to the kind of data I am retrieving, I cannot define this. The data retrieved from the server could have any column/field names, and any number of columns. It is not complex JSON however.
How do I get my grid to populate with this data?
I have created a new Datasource and mapped it to the existing one outside the success method.
Can you try this one below :
var newDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Utilities/Report/Run",
dataType: "json",
data: JSON.stringify(model),
error: function (result) {
options.error(result);
}
}
}
});
var d1 = $("#grid").data("kendoGrid");
d1.dataSource.data([]);
d1.setDataSource(newDataSource );
make changes as per your necessity if I have missed any . Kendo data binding is always confusing :D
Kendo DataSource is very powerful. Ideally, you do not need to make a manual Ajax call. Instead, DataSource can Ajax request data from URL by itself, if Grid needs data.
https://jsfiddle.net/6gxqsrzu/
$(function() {
var dataSource = new kendo.data.DataSource({
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: {
type: "number"
},
Freight: {
type: "number"
},
ShipName: {
type: "string"
},
OrderDate: {
type: "date"
},
ShipCity: {
type: "string"
}
}
}
},
serverPaging: true,
pageSize: 5,
serverSorting: true,
sort: {
field: 'OrderDate',
dir: 'asc'
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight", {
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name"
}, {
field: "ShipCity",
title: "Ship City"
}
]
});
});
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>
<div id="grid"></div>
I'm attempting to get a row of data based on button click event. I can manage to find the row and read the results as text, but I want the data cast as a string or an object. Below is my current code:
$.ajax({
url: "SympsService.asmx/GetSymptoms",
method: "post",
dataType: "json",
data: JSON.stringify({
organ_name: "toes"
}),
contentType: "application/json",
success: function(data) {
var sympList = 'GetSymptoms' ? JSON.parse(data.d) : data.d;
createDataTable('#symptomsTable', sympList);
function createDataTable(target, data) {
$(target).DataTable({
destroy: true,
paging: false,
searching: false,
info: false,
data: data,
columnDefs: [{
targets: [-1],
render: function() {
return "<button type='button'>" + ('Choose') + "</button>"
}
}],
columns: [{
'data': 'Sympt',
'title': 'toes Symptoms'
}, {
'data': null,
'title': 'Action'
}]
});
}
$('#symptomsTable').on("click", "tbody button", function() {
var id = $(this).closest("tr").find("td:nth-child(1)").text(); //this show perfectly
var id = $(this).closest("tr").find("td:nth-child(1)").data(); //this show undefined
var id = $(this).closest("tr").find("td:nth-child(1)").toString(); //this show {object Object}
console.log(id);
})
},
});
Any kind of help is appreciated.
To find the data object for the whole row:
$("#symptomsTable').DataTable().rows($(this).closest("tr")).data()
to find it for the particular cell:
$("#symptomsTable").DataTable().cells($(this).closest("td").siblings().eq(0)).data()