I use jqGrid add new record, but i can't put data from grid to json string.
When i run, return code:
error Status: 'Unsupported Media Type'. Error code: 415
And my code:
$(document).ready(function () {
jQuery("#jQGridDemo").jqGrid({
url: 'http://192.168.1.59:8080/sunrise/api/v1/warehouse/getById/1',
mtype: "GET",
contentType: "application/json",
datatype: "json",
colNames: ['wareHouseID', 'name' , 'fullname' , 'company', 'address'],
colModel: [
{ name: 'wareHouseID', index: 'wareHouseID', width: 150,editable:false, editoptions:{readonly:true, size:10}, hidden:true},
{ name: 'name', index: 'name', width: 150,editable:true, editoptions:{size:30}},
{ name: 'fullname', index: 'fullname', width: 150,editable:true,editoptions:{size:30}},
{ name: 'company', index: 'company', width: 150,editable:true,editoptions:{size:30}},
{ name: 'address', index: 'address', width: 150,editable:true,editoptions:{size:30}}
],
rowNum: 10,
rowList:[10,20,30],
width: 1290,
sortname: 'wareHouseID',
sortorder:"desc",
height:235,
gridview: true,
viewrecords: true,
caption: "List User Details",
editurl:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/update",
pager: "#jQGridDemoPager",
ajaxRowOptions : {
type :"POST",
contentType :"application/json",
dataType :"json"
},
serializeRowData: function(postData){
return JSON.stringify(postData);
}
});
$("#jQGridDemo").jqGrid('navGrid','#jQGridDemoPager',
{edit:true, add:true, del:false, search:true},
// Edit options
{
type:"PUT",
url:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/update",
closeAfterEdit:true,
reloadAfterSubmit:true,
onclickSubmit: function(params, postData) {
return JSON.stringify(postData);
},
afterSubmit: function(response, postData) {
var res = jQuery.parseJSON(response.responseText);
return [true, "", res.d];
}
},
//Add option
{
type:"POST",
url:"http://192.168.1.59:8080/sunrise/api/v1/warehouse/new",
closeAfterAdd:true,reloadAfterSubmit:true,
onclickSubmit: function(params, postData) {
return JSON.stringify(postData);
},
afterSubmit: function(response, postData) {
var res = jQuery.parseJSON(response.responseText);
return [true, "", res.d];
}
}
);});
Could you help me to find a problem and how to fix it? Tks very much.
There are many unclear parts in your code. Nevertheless I guess that the main problem which you have is the following: you use ajaxRowOptions to set contentType and you use serializeRowData to serialize the data from request as JSON. The problem is: you use form editing, but ajaxRowOptions and serializeRowData will be used only in case of inline editing.
So you should use
ajaxEditOptions: { contentType :"application/json" },
serializeEditData: function (postData) {
return JSON.stringify(postData);
}
You have to remove onclickSubmit which returns JSON.stringify(postData) additionally.
I hope it should solve the problem. If it will not help then you should write first of all which version of jqGrid you use and which fork of jqGrid you use (free jqGrid, Guriddo jqGrid JS or some old jqGrid in version <= 4.7). You should write additionally more information about the server which reruns the error "'Unsupported Media Type'. Error code: 415".
Related
I'm using OData v4 with Web API to communicate with my AngularJS web application.
More specifically I'm trying to display my data using Kendo UI Grid.
My problem is, that my Web API does not return the correct metadata, resulting in Kendos datasource not being able to display the data.
I'm doing paging, and to do that I need the "count" property in my response for Kendo UI Grid datasource to be able work properly.
The response I'm expecting the Web API should look something like this:
http://docs.oasis-open.org/odata/odata-json-format/v4.0/errata02/os/odata-json-format-v4.0-errata02-os-complete.html#_Toc403940644
However, the result I'm seeing in the response is:
{
"#odata.context":"http://localhost:1983/odata/$metadata#TestReports","value":[
{
"Id":1,"Name":"Test Testesen","Purpose":"Kendo UI Grid Test","Type":"Rumraket","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":2,"Name":"Gunner Testesen","Purpose":"OData Web API Test","Type":"Sutsko","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":3,"Name":"Bertram Didriksen","Purpose":"Server Paging Test","Type":"Flyver","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":4,"Name":"Oluf Petersen","Purpose":"Test","Type":"B\u00e5d","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
},{
"Id":5,"Name":"Alfred Butler","Purpose":"Opvartning","Type":"Batmobil","ReportedDate":"2015-02-04T10:03:59.4173323+01:00"
}
]
}
My code for retrieving the data is:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "odata"
},
parameterMap: function (options, type) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
console.log(paramMap);
delete paramMap.$inlinecount; // <-- remove inlinecount parameter
delete paramMap.$format; // <-- remove format parameter
console.log(paramMap);
return paramMap;
}
},
schema: {
data: function (data) {
return data; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data.length; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};
My WebApiConfig class is corrently like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.InsertRange(0, ODataMediaTypeFormatters.Create());
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "odata",
model: GetModel()
);
}
public static Microsoft.OData.Edm.IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<TestReport>("TestReports");
return builder.GetEdmModel();
}
}
Does anyone have any suggestions on how I get the Web API to return the correct metadata?
Apparently Kendo UI Grid is not supporting OData v4.
The fix was to modify the parameterMap of the Kendo datasource, and tell it to use $count instead of $inlinecount.
Besides that I had to tell the schema to read "#odata.count" as the "total" value.
After I edited the before posted code to the ode below, I got the correct data in my response:
$scope.pendingReports = {
dataSource: {
type: "odata",
transport: {
read: {
beforeSend: function (req) {
req.setRequestHeader('Accept', 'application/json;odata=fullmetadata');
},
url: "/odata/TestReports",
dataType: "json"
},
parameterMap: function (options, type) {
var d = kendo.data.transports.odata.parameterMap(options);
delete d.$inlinecount; // <-- remove inlinecount parameter
d.$count = true;
return d;
}
},
schema: {
data: function (data) {
return data.value; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data['#odata.count']; // <-- The total items count is the data length, there is no .Count to unpack.
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
},
sortable: true,
pageable: true,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns: [
{
field: "Name",
title: "Navn"
}, {
field: "ReportedDate",
title: "Indberetet den"
}, {
field: "Purpose",
title: "Formål"
}, {
field: "Type",
title: "Type"
}, {
field: "options",
title: "Muligheder"
}
]
};
For some reason I seem to be unable to get any more than the following in the Kendo UI Grid:
HTML:
<div id="grid"></div>
<script>
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "POST",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
})
$("#grid").kendoGrid(
{
dataSource: remoteDataSource,
columns: [
{
title: "Title",
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell"
},
width: 600,
filterable: true
},
{
title: "Activity Type",
headerAttributes: {
},
attributes: {
"class": "table-cell",
style: "text-align:center"
},
width: 100,
filterable: true
},
{
title: "Specialty",
filterable: true,
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell",
style: "text-align:center"
}
},
{
title: "Total Credits",
format: "{0}",
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell",
style: "text-align:center"
}
}
],
height: 430,
scrollable: true,
sortable: true,
pageable: true,
filterable: {
extra: false,
operators: {
string: {
contains: "Contains",
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
},
number: {
eq: "Is equal to",
neq: "Is not equal to",
gte: "Greater Than",
lte: "Less Than"
}
}
}
});
</script>
This is the JSON that is returned to it:
[
{"ActivityID":367,"Title":"Non Webinar Test For Calendar","ActivityType":"Other","TotalCredits":2,"Specialty":"[AB] [AE]"},
{"ActivityID":370,"Title":"Stage - Test SI Changes Part II","ActivityType":"Other","TotalCredits":2,"Specialty":"[NE]"},
{"ActivityID":374,"Title":"Webinar Test Event For Calendar","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[FE] [NE] "},
{"ActivityID":401,"Title":"Module #1 Webinar: Learn Stuff","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[AB] ",},
{"ActivityID":403,"Title":"Module #3 Webinar: Learn Even More Stuff","ActivityType":"Webinar","TotalCredits":2,"Specialty":"[AB] [AE]",}
]
I feel like I'm really close but am missing the last piece. Any help would be GREATLY appreciated as I'm on a deadline.
common troubles are with missing schema attribute !
add it to grid's - datasource, and check if it is set when you make your json.
(when plain array is serialized/to_json, the data array needs a property indicating the shema)
here an example to make it clear:
js: sample grid initialisation / datasource:
$("#grid").kendoGrid({ dataSource: { transport: { read: "/getdata/fromthisurl" }, schema: { data: "data" } } });
when you make / output your json, see if shema information is in the encoded result:
php:
$somedata= get_my_data();
header("Content-type: application/json");
echo "{\"data\":" .json_encode($somedata). "}";
or:
$viewdata['data'] = get_my_data();
header("Content-type: application/json");
echo (json_encode($viewdata));
so the json that is sent to the grid would look like:
{data:
[
{item}
{item}
]
}
instead of just:
[
{item}
{item}
]
Code looks good. I wonder if you change data source creation as below . Change type from POST to GET and see if it works,
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "GET",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
})
Try this,
$(document).ready(function () {
var remoteDataSource = new kendo.data.DataSource(
{
transport:
{
read: {
type: "POST",
dataType: "json",
url: "/home/getopportunities/"
}
},
pageSize: 4
});
});
You can see what part of code raise an exception in some debug tool (I'd recommend you Chrome's DevTools (just press F12 key in Chrome).
I'm pretty sure the problem is misssing field attribute in your grid's columns array, so Kendo don't know what data from datasource to display in what column of grid.
columns: [
{
field: "Title", // attr name in json data
title: "Title", // Your custom title for column (it may be anything you want)
headerAttributes: {
style: "text-align:center"
},
attributes: {
"class": "table-cell"
},
width: 600,
filterable: true
},
Don't forget to change request type from "POST" to "GET".
What I found when inspecting the JSON coming back from the grid datasource json query was the field names were being JavaScripted -- what was ActivityID in C# became activityID on the wire...
This is unclean, and I discovered it by accident, but what worked for me was returning Json(Json(dataList)) from the controller instead of Json(dataList).
Q1.json is working (index.json). but i cant display in the jqgrid. i think colmodel names is the problem.Is it required that the colModel name is from database field? i want to display in jqgrid is from my select statements and those variables is from different tables. Not only one table but 3 tables.
Q2.Same row should be displayed in jqgrid but from different table. is it possible?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'{{=URL(r=request,f='call',args=['json','index'])}}',
data: "{}",
datatype: 'json',
mtype: 'GET',
contentType: "application/json; charset=utf-8",
complete: function(jsondata, stat) {
if (stat == "success") {
var thegrid = jQuery("#list")[0];
thegrid.addJSONData(JSON.parse(jsondata.responseText).d);
}
},
colNames:['code','name','max','min','quantity','amount'],
colModel :[
{name:CODE',index:'CODE', width:55},
{name:'Name', index:'Name',width:100},
{name:'MAX(table2.hour)', index:'MAX(hour)',width:100},
{name:'MIN(tabl2.hour)', index:'MIN(hour)',width:100},
{name:'SUM(quantity)', index:'SUM(quantity)',width:180},
{name:'SUM(amount)', index:'SUM(amount)',width:180}
],
hidegrid: false,
scrollOffset:0,
pager: '#pager',
rowNum:100,
shrinkToFit:false,
//rowList:[10,20,30,50],
//sortname: 'id',
//sortorder: 'desc',
viewrecords: false,
width: "100%",
height: "100%",
caption: 'SALES Grid'
});
});
</script>
{"rows": [0, {"table1": {"Name": "dyon"}, "_extra": {"MAX(table2.hour)": "20130514214301484", "MIN(table2.hour)": "20130514052610093", "SUM(table2.quantity)": 2115.854, "SUM(table2.amount)": 90089.15}, "table3": {"CODE": 1800}}]}
NOTE: i want to display the data in one page only.when i run the index.html it contains rows but it is blank and theres a rows contains 0 per cell.When i run the index.json it contains the data i needed. Im newbie to python. thanks!
The first problem is that you use many options of jqGrid which not exist (see the documentation): data, contentType, complete. You remove the options or use some other options which do what you probably tried to do.
The second problem is the usage of properties in JSON input which has dots inside (like SUM(table2.quantity) for example). To be able to read such properties you have to define jsonmap as function. For example
jsonmap: function (obj) {
return obj._extra["SUM(table2.quantity)"];
}
Because the JSON data have 0 as the first element you will have to fix the above code to somthing like
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.quantity)"]: "";
}
The first demo demonstrate the results:
The best would be to fix your server code to remove the unneeded 0 item from rows array. If you can't do this on the server side you can do this on the client side inside of beforeProcessing callback.
The demo displays
It uses the following JavaScript code
$("#list").jqGrid({
url: "CrazyGirl.json", // need be changed to youth
datatype: "json",
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (data) {
return JSON.stringify({}); // send empty object (???)
},
colNames: ["code", "name", "max", "min", "quantity", "amount"],
colModel: [
{name: "code", width: 55, jsonmap: "table3.CODE"},
{name: "name", width: 100, jsonmap: "table1.Name"},
{name: "max", width: 120,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["MAX(table2.hour)"]: "";
}},
{name: "min", width: 120,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["MIN(table2.hour)"]: "";
}},
{name: "quantity", width: 100,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.quantity)"]: "";
}},
{name: "amount", width: 100,
jsonmap: function (obj) {
return typeof obj === "object"? obj._extra["SUM(table2.amount)"]: "";
}}
],
jsonReader: { repeatitems: false },
hidegrid: false,
pager: "#pager",
rowNum: 1000,
shrinkToFit: false,
height: "100%",
caption: "SALES Grid"
});
When I pass the URL I am getting a no response from the url otherwise if I specify the corresponding WCF service page which is included in my project it is working is it any cross domain issue what would be the possible issue
<form id="sform" runat="server">
<table id="flex2" style="display:none"></table>
<script type="text/javascript">
$(document).ready(function () {
var user_id = 1;
var data = { UserID: user_id };
$("#flex2").flexigrid({
useInlineEditor: true,
//singleSelect: true,
rowClick: function (row) {
//var r=this.DataSource.rows[row.rowIndex];
//var p=$(row).offset();
//alert(r[this.DataSource.key]+" "+r.Name+" offset:"+p.top+","+p.left);
//this.grid.inlineEditor.edit(row);
},
url: 'http://192.168.10.91:5001/Service.svc/GetStates',
method: 'POST',
dataType: 'json',
colModel: [
{ display: 'Hours', name: 'hours', width: 40, sortable: true, align: 'center' },
{ display: 'DOC', name: 'doc', width: 180, sortable: true, align: 'left' },
],
searchitems: [
{ display: 'Type', name: 'cmetype' }
],
onError: function (jqXHR, textStatus, errorThrown) {
alert("flexigrid failed " + errorThrown + jqXHR + textStatus);
},
sortname: "type",
sortorder: "asc",
usepager: true,
title: 'States',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 800,
height: 200
});
});
//This function adds paramaters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit
function addFormData() {
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
$("#flex2").flexOptions({ params: dt });
return true;
}
$('#sform').submit(function () {
$('#flex2').flexOptions({ newp: 1 }).flexReload();
return false;
});
</script>
</form>
Make sure that the svc service is accesibile and that it can accept post requests.
If all works well, check that the response is JSON and is valid.
I would like to post json data to the server (REST API). When I now double click on a row to edit inline, 'serializeRowData' is called and my server receives a json formatted message in the body. But when I click on the little '+' icon in the pager, 'serializeRowData' is not called.
I'm using version:
JQuery 1.5.2
JQGrid 4.4.1
My Grid looks like:
$("#dbgrid").jqGrid({
url: 'rest/config/dbs',
editurl: 'rest/config/db',
datatype: "json",
height: 255,
width: 600,
colNames:['ID', 'Env', 'Hostname', 'Name', 'Port', 'Service Name', 'SID'],
colModel:[
{name:'id',index:'id', width:30, sorttype:'int'},
{name:'env',index:'env', editable:true, width:50},
{name:'hostName',index:'hostName', editable:true, width:200},
{name:'name',index:'name', editable:true, width:200},
{name:'port',index:'port', editable:true, width:30},
{name:'serviceName',index:'name', editable:true, width:30},
{name:'sid',index:'sid', editable:true, width:30}
],
jsonReader: {
repeatitems: false,
id: "id",
},
rowNum:50,
rowTotal: 2000,
rowList : [20,30,50],
loadonce:false,
mtype: "GET",
rownumbers: true,
rownumWidth: 40,
gridview: true,
pager: '#pdbgrid',
sortname: 'id',
viewrecords: true,
sortorder: "asc",
caption: "Database Servers" ,
ajaxRowOptions : {
type :"POST",
contentType :"application/json; charset=utf-8",
dataType :"json"
},
serializeRowData: function(postdata){
return JSON.stringify(postdata);
}
});
$("#dbgrid").jqGrid('navGrid','#pdbgrid',{edit:true,add:true,del:true}
Am I missing something?
Any help, along with examples, would be hugely appreciated.
Because that doesn't come in inline editing. You can change last line of your code like this.
$("#dbgrid").jqGrid('navGrid','#pdbgrid',{edit:true,add:true,del:true},
{//edit parameters},
{//add parameters
serializeEditData: function (postdata) {}
},
{//delete parameters}
);
Now if you want to serialize edit data then same function you can write in edit parameters also. This function works for both add and edit. For delete, it will be serializeDelData.
I hope it helps you.
If someone has the same problem here a working solution:
...
$("#dbgrid").jqGrid('navGrid','#pdbgrid',
{edit:true,add:true,del:true},
{
//edit parameters
ajaxEditOptions: jsonOptions,
serializeEditData: createJSON,
closeAfterEdit: true
},
{
//add parameters
ajaxEditOptions: jsonOptions,
serializeEditData: createJSON,
closeAfterAdd: true
},
{
//delete parameters
ajaxDelOptions: jsonOptions,
serializeDelData: createJSON
}
);
var jsonOptions = {
type :"POST",
contentType :"application/json; charset=utf-8",
dataType :"json"
};
function createJSON(postdata) {
if (postdata.id === '_empty')
postdata.id = null; // rest api expects int or null
return JSON.stringify(postdata)
}