JQWidget Grid - rowdata changing even before statement to do so - javascript

I am having some trouble with a JQWidget-jqxGrid i'm developing. I will like to change the format information is being send to an API from a row edition. I need to change some Dates to a specific string notation. This is the code i am using right now:
updaterow: function (rowid, rowdata, commit)
{
//console.log(rowdata);
var output = rowdata;
for (property in output) {
if (output[property] instanceof Date && schema.properties[property].format === "time") {
output[property] = output[property].getHours() + ":" + output[property].getMinutes();
//console.log('hola');
}
if (output[property] instanceof Date && schema.properties[property].format === "date")
{
output[property] = output[property].getFullYear() + "-" + output[property].getMonth() + 1 + '-' + output[property].getDate();
}
}
/*console.log(event.args.row);*/
console.log(output);
console.log(rowdata);
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/api/" + entity + "/" + rowdata.uid,
cache: false,
method: "put",
data: JSON.stringify(rowdata),
processData: false,
headers: {
"RequestVerificationToken": token,
"Content-type": "Application/json"
},
success: function () {
console.log("Okey dokey!");
commit(true);
},
error: function () {
alert("El dato no se ha actualizado correctamente");
}
});
}
I tried many things before doing this. Originally, i was doing the update on a “oncelledit” event, the problem was the same (And this is like some kind of paranormal activity for me):
As you can see, i am doing the reformating of data in output variable, instead of rowdata. Even so, before output variable gets modified for the ajax request, if i uncomment “console.log(rowdata);”, data will already be changed even before the “for” scope where data is modified. How this is really possible? I have checked cache by using another browser, but no luck.
Although data is correctly posted to my API with this code, data format is changed on the grid displayed to the user, and data gets ouwfull. I will like to send the information in the appropriate format, but not to change format data shown in the grid.
This is how the data is shown before edition:
fecha de inicio | hora de inicio
1/10/2018 | 8:00 AM
And this is after edition:
fecha de inicio | hora de inicio
2001-01-1 |13:0
I post my full code just in case:
—JSGrid.js—
$.ajaxSetup({ cache: false });
var FKSources = [];
var FKAdapters = {};
var dataFieldsArr = [];
var columnsArr = [];
var FKPropertySelection;
var entity;
var schema;
function createGrid()
{
$.ajax({
url: "/api/" + entity + "/schema",
success: function (data) {
schema = data;
for (property in data.properties) {
if (data.properties[property]["type"].indexOf("lhcrud") > -1) {
FKSources.push({
datatype: "json",
datafields:
[
{ name: data.fkAttributes[property] },
{ name: 'id', type: 'int' }
],
id: 'id',
url: '/api/' + data.properties[property]["type"].substring(data.properties[property]["type"].indexOf("models.") + "models.".length)
});
FKAdapters[property] = new $.jqx.dataAdapter(FKSources[FKSources.length - 1]);
dataFieldsArr.push({
name: property + 'Id',
value: property + 'Id',
values:
{
source: FKAdapters[property].records,
value: 'id',
label: data.fkAttributes[property]
},
type: 'int'
});
dataFieldsArr.push({
name: property + 'Nombre',
type: 'string',
map: property + '>' + data.fkAttributes[property]
});
columnsArr.push(
{
text: data.properties[property]["title"],
columntype: 'dropdownlist',
datafield: property + 'Id',
width: 150,
filtertype: 'checkedlist',
displayfield: property + 'Nombre',
createeditor: function (row, value, editor) {
editor.jqxDropDownList({ source: FKAdapters[FKPropertySelection], displayMember: data.fkAttributes[FKPropertySelection], valueMember: 'id' });
}
}
);
}
else if (data.properties[property]["type"].indexOf("integer") > -1) {
dataFieldsArr.push({ name: property, type: 'int' });
columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 80, cellsalign: 'right' });
}
else if (data.properties[property]["type"].indexOf("boolean") > -1) {
dataFieldsArr.push({ name: property, type: 'bool' });
columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 65, columntype: 'checkbox' });
}
else if (data.properties[property]["format"].indexOf("date") > -1) {
dataFieldsArr.push({ name: property, type: 'date' });
columnsArr.push({
text: data.properties[property]["title"], datafield: property, width: 150, columntype: 'datetimeinput', cellsalign: 'right', cellsformat: 'd'
});
}
else if (data.properties[property]["format"].indexOf("time") > -1) {
dataFieldsArr.push({ name: property, type: 'date' });
columnsArr.push({
text: data.properties[property]["title"], datafield: property, width: 100, columntype: 'datetimeinput', cellsalign: 'right', cellsformat: 't', createeditor: function (row, column, editor) {
editor.jqxDateTimeInput({
showTimeButton: true,
showCalendarButton: false
});
}
});
}
else {
dataFieldsArr.push({ name: property, type: 'string' });
columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 150 });
}
}
columnsArr.push({
text: 'Delete', datafield: 'Delete', columntype: 'button', width: 90, cellsrenderer: function () {
return "Delete row";
}, buttonclick: function (row) {
var deleteConfirm = confirm("Sure?");
if (deleteConfirm) {
var id = $("#jqxgrid").jqxGrid('getrowid', row);
deleteEntity(entity, id, $('input[name="__RequestVerificationToken"]').val());
$('#jqxgrid').jqxGrid('deleterow', id);
}
}
});
var source =
{
datatype: "json",
datafields: dataFieldsArr,
id: 'id',
url: '/api/' + entity,
addrow: function (rowid, rowdata, position, commit) {
var token = $('input[name="__RequestVerificationToken"]').val();
//console.log(rowid);
//console.log(rowdata);
$.ajax({
url: "/api/" + entity,
method: "post",
data: JSON.stringify(rowdata),
processData: false,
headers: {
"RequestVerificationToken": token,
"Content-type": "Application/json"
},
success: function () {
commit(true);
//reload Data in order to manage correctly new data
$("#jqxgrid").jqxGrid(
{
source: dataAdapter,
sortable: true,
filterable: true,
editable: true,
showeverpresentrow: true,
everpresentrowposition: "top",
selectionmode: 'singlecell',
editmode: 'dblclick',
theme: 'light',
columns: columnsArr
});
},
error: function (xhr) {
console.log(xhr);
commit(false);
}
});
},
updaterow: function (rowid, rowdata, commit)
{
//console.log(rowdata);
var output = rowdata;
for (property in output) {
if (output[property] instanceof Date && schema.properties[property].format === "time") {
output[property] = output[property].getHours() + ":" + output[property].getMinutes();
//console.log('hola');
}
if (output[property] instanceof Date && schema.properties[property].format === "date")
{
output[property] = output[property].getFullYear() + "-" + output[property].getMonth() + 1 + '-' + output[property].getDate();
}
}
/*console.log(event.args.row);*/
console.log(output);
console.log(rowdata);
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/api/" + entity + "/" + rowdata.uid,
cache: false,
method: "put",
data: JSON.stringify(rowdata),
processData: false,
headers: {
"RequestVerificationToken": token,
"Content-type": "Application/json"
},
success: function () {
console.log("Okey dokey!");
commit(true);
},
error: function () {
alert("El dato no se ha actualizado correctamente");
}
});
}
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid(
{
source: dataAdapter,
width: '100%',
sortable: true,
filterable: true,
editable: true,
showeverpresentrow: true,
everpresentrowposition: "top",
selectionmode: 'singlecell',
editmode: 'dblclick',
theme: 'light',
columns: columnsArr
});
},
error: function () {
alert("Error Getting Data");
}
});
}
$("#jqxgrid").on('cellselect', function (event) {
FKPropertySelection = event.args.datafield.substring(0, event.args.datafield.indexOf('Id'));
});
—JSGrid.cshtml—
#{
ViewData["Title"] = "JSGrid";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>JSGrid for #ViewBag.entity</h2>
#Html.AntiForgeryToken()
<div id="jqxgrid">
</div>
#section scripts
{
<link rel="stylesheet" href="~/lib/jqwidgets/styles/jqx.base.css" type="text/css" />
<link rel="stylesheet" href="~/lib/jqwidgets/styles/jqx.light.css" type="text/css" />
<script type="text/javascript" src="~/lib/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxmenu.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxlistbox.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxdropdownlist.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxcheckbox.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxdatetimeinput.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxcalendar.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxtooltip.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.selection.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.columnsresize.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.filter.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.sort.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.pager.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.grouping.js"></script>
<script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.edit.js"></script>
<script type="text/javascript" src="~/js/JSGrid.js"></script>
<script>
entity = '#ViewBag.entity';
createGrid();
</script>
}
Thanks in advance!

All right! I found my solution here:
https://www.jqwidgets.com/community/topic/rowdata-changed-even-before-statement-to-do-so/#post-98256
and here:
https://www.jqwidgets.com/community/topic/difference-between-refreshdata-and-updatebounddata/
(¡Haya PAZ! - Les luthiers)
I partially solved my issue reloading binded data with 'updatebounddata' method from jqxgrid.
Just in case someone has the same problem, i will leave here my updateRow function updated. Look at the ajax block:
updaterow: function (rowid, rowdata, commit)
{
//console.log(rowdata);
var output = rowdata;
for (property in output) {
if (output[property] instanceof Date && schema.properties[property].format === "time") {
output[property] = output[property].getHours() + ":" + output[property].getMinutes();
//console.log('hola');
}
if (output[property] instanceof Date && schema.properties[property].format === "date")
{
output[property] = output[property].getFullYear() + "-" + (output[property].getMonth() + 1) + '-' + output[property].getDate();
}
}
//console.log(event.args.row);
//console.log(output);
//console.log(rowdata);
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/api/" + entity + "/" + rowdata.uid,
cache: false,
method: "put",
data: JSON.stringify(rowdata),
processData: false,
headers: {
"RequestVerificationToken": token,
"Content-type": "Application/json"
},
success: function () {
console.log("Okey dokey!");
commit(true);
$("#jqxgrid").jqxGrid('updatebounddata');
},
error: function () {
alert("El dato no se ha actualizado correctamente");
$("#jqxgrid").jqxGrid('updatebounddata');
}
});
}
Hope this will help someone in the future!

Related

Error passing JSON object from WebMethod (C#)

I have a C# WebMethod that gets some data from my SQL database and then turns it into a JSON string.
Here is the WebMethod
[WebMethod]
public object getCustomers() {
string constr = ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.Constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT custid, cust_name FROM [dbo].[customers] WHERE archive = 'No'"))
{
cmd.Connection = con;
List<Customers> customers = new List<Customers>();
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new Customers
{
custid = sdr["custid"].ToString(),
cust_name = sdr["cust_name"].ToString(),
});
}
con.Close();
String result = JsonConvert.SerializeObject(customers);
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(result);
return result;
}
}
}
}
I am them trying to pass this data on the client side, using JavaScript.
Here is my JS
function buildSelect(response) {
alert(JSON.stringify(response));
var $tulem = $("<select><option value=''>All</option></select>");
$.each(JSON.parse(response).rows, function (i, item) {
$("<option></option>", { value: item.custid })
.text(item.custid)
.appendTo($tulem);
});
return $tulem;
}
The JSON.Parse fails with following errors
XML Parsing Error: syntax error
Location: https://localhost:44338/WebService1.asmx/getCustomers
Line Number 1, Column 1: getCustomers:1:1
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 722 of the JSON data
If I return my JSON the console it looks like this.
"[{\"custid\":\"ACC001\",\"cust_name\":\"Accenda Limited\"},{\"custid\":\"ANI001\",\"cust_name\":\"Animal Friends\"},{\"custid\":\"APP001\",\"cust_name\":\"Appello\"},{\"custid\":\"ATL001\",\"cust_name\":\"Atlas Contract Furniture\"},{\"custid\":\"BNS001\",\"cust_name\":\"BNS Ltd\"},{\"custid\":\"HAR001\",\"cust_name\":\"Harrow Health\"},{\"custid\":\"IND001\",\"cust_name\":\"Indigo Integrated Solutions\"},{\"custid\":\"MER001\",\"cust_name\":\"Merton Health Limited\"},{\"custid\":\"POL001\",\"cust_name\":\"Polyhose (UK) Ltd\"},{\"custid\":\"PUR001\",\"cust_name\":\"Purbeck School\"},{\"custid\":\"QUE001\",\"cust_name\":\"Queen Elizabeth's School\"},{\"custid\":\"SER001\",\"cust_name\":\"Serbus Limited\"},{\"custid\":\"STS001\",\"cust_name\":\"STS Defence\"},{\"custid\":\"WIM001\",\"cust_name\":\"Wimborne Academy Trust\"}]<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<anyType xmlns:q1=\"http://www.w3.org/2001/XMLSchema\" d1p1:type=\"q1:string\" xmlns:d1p1=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://tempuri.org/\">[{\"custid\":\"ACC001\",\"cust_name\":\"Accenda Limited\"},{\"custid\":\"ANI001\",\"cust_name\":\"Animal Friends\"},{\"custid\":\"APP001\",\"cust_name\":\"Appello\"},{\"custid\":\"ATL001\",\"cust_name\":\"Atlas Contract Furniture\"},{\"custid\":\"BNS001\",\"cust_name\":\"BNS Ltd\"},{\"custid\":\"HAR001\",\"cust_name\":\"Harrow Health\"},{\"custid\":\"IND001\",\"cust_name\":\"Indigo Integrated Solutions\"},{\"custid\":\"MER001\",\"cust_name\":\"Merton Health Limited\"},{\"custid\":\"POL001\",\"cust_name\":\"Polyhose (UK) Ltd\"},{\"custid\":\"PUR001\",\"cust_name\":\"Purbeck School\"},{\"custid\":\"QUE001\",\"cust_name\":\"Queen Elizabeth's School\"},{\"custid\":\"SER001\",\"cust_name\":\"Serbus Limited\"},{\"custid\":\"STS001\",\"cust_name\":\"STS Defence\"},{\"custid\":\"WIM001\",\"cust_name\":\"Wimborne Academy Trust\"}]</anyType>"
What am I doing wrong, what can I do to change this into a standard clean JSON string?
UPDATED
This is where the WebMethod is called from, its the dataURL, for a field called cust_name, defined in the editoptions of a JQGRID.
jQuery("#jqquotes").jqGrid({
url: '../We
bService1.asmx/getDataQuotes',
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) {
return typeof obj.d.rows === "string" ? $.parseJSON(obj.d.rows) : obj.d.rows;
},
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.records; },
repeatitems: false
},
loadComplete: function () {
$('#jqquoteitems').trigger('reloadGrid');
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
onSelectRow: function () {
showDetailsGrid();
},
height: 'auto',
//autowidth: true,
rowNum: 5,
rowList: [5, 10, 15],
colNames: ['Doc ID', 'Quote #', 'Summary', 'Date', 'Customer', 'Contact', 'custid'],
colModel: [
{ name: 'docid', key: true, index: 'docid', width: 55, editable: true },
{ name: 'quote_number', index: 'quote_number', width: 45, editable: true },
{ name: 'summary', index: 'summary', width: 160, editable: true, edittype: 'textarea' },
{
name: 'quote_date', formatter: 'date', datefmt: "d-m-Y", editoptions: { dataInit: initDateEdit },
formatoptions: { srcformat: "d/m/Y H:i:s", newformat: "d-m-Y" }, index: 'quote_date', width: 60, editable: true
},
{
name: 'cust_name', index: 'cust_name', width: 140, align: "left", editable: true, edittype: "select",
editoptions: {
dataUrl: '/WebService1.asmx/getCustomers',
buildSelect: buildSelect
}
},
...
It's crashing because the end of your JSON string you have "<anyType>" which is not a parseable for JSON.

Bug with kendo grid,for closing pop up editor,you need to press cancel many times

its over a week im dealing with a strange behavior of kendo grid ,let me split my problem, for better understanding ,i have a autocomplete text box ,after I press ENTER,it binds my grid,when I press "add new record" on my kendo grid,if I press cancel,the pop up will be closed,BUTTT after second search and the add new record,if press cancel,this time needs 2times pressing,3d time needs 3times pressing.......made me crazy,badly need your help
Here is the code
$(document).keypress(function (e) {
var myResult;
var modelProducerResult;
var temp = null;
var mydata;
var mydata_deviceType;
var modelProducerDrpList;
if (e.which == 13) {
var i = 0;
debugger;
var flag = 0;
// $('#turbingrid').data().kendoGrid.refresh();
var drp = document.getElementById('autocomplete').value;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("turbineDeviceDetail","AdminTool")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "turbine": drp, }),
success: function (result) {
//debugger;
myResult = result;
var flg = "s";
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("producersDevice","AdminTool")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "flg": flg, }),
success: function (data) {
// debugger;
mydata = data;
}
})
var flg_dvType = "s";
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("deviceTypeList","AdminTool")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "flg": flg_dvType, }),
success: function (data) {
// debugger;
mydata_deviceType = data;
}
});
dataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
options.success(result); // where data is the local data array
},
create: function (options) {
if ($("input[name='DeviceIP']").val() == "" || $("input[name='TurbineId']").val() == "") {
alert("DeviceIP and TurbineID could not be blank ");
$("input[name='DeviceIP']").css("background-color", "red");
$("input[name='TurbineId']").css("background-color", "red");
}
else
$.ajax({
type: "POST",
url: "#Url.Action("AddDeviceToTurbine","AdminTool")",
data: options.data.models[0],
dataType: "json",
success: function (data) {
options.success(data);
alert("New Device Has Been Inserted");
//var e = $.Event("keypress", { which: 13 });
//$('#autocomplete').trigger(e);
},
//error: function (data) {
// options.error(data);
// alert("Insert New Data Has Been Failed");
// alert(data);
//},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
},
update: function (options) {
if ($("input[name='DeviceIP']").val() == "" || $("input[name='TurbineId']").val() == "") {
alert("DeviceIP and TurbineID could not be blank ");
$("input[name='DeviceIP']").css("background-color", "red");
$("input[name='TurbineId']").css("background-color", "red");
}
else
$.ajax({
type: "POST",
url: "#Url.Action( "update_grid","AdminTool")",
data: options.data.models[0],
dataType: "json",
success: function (data) {
options.success(data);
alert("Update Has Been Done!");
var value = document.getElementById('autocomplete').value;
var e = $.Event("keypress", { which: 13 });
$('#autocomplete').trigger(e);
},
error: function (data) {
options.error(data);
alert("Update Failed!");
},
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 40,
schema: {
//data: employee,
model: {
id: "DeviceIP",
fields: {
DeviceIP: { editable: true, nullable: false },
//Producer: { type:"string" },
//3 Model: { type: "string" },
DeviceType: { type: "string" },
Description: { type: "string" },
Username: { type: "string" },
Password: { type: "string" },
PublicIP: { type: "string" },
ModelProducer: { type: "string" },
Model: { type: "string" },
Producer: { type: "string" },
TurbineId: { type: "string" }
//UnitPrice: { type: "number", validation: { required: true, min: 1} },
//Discontinued: { type: "boolean" },
//UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
$("#turbingrid").kendoGrid({
// debugger;
dataSource: dataSource,
scrollable: false,
//toolbar: ["create"],
toolbar: [
{
name: "create",
text: "ADD NEW DEVICE"
}
],
columns: [
{ field: 'DeviceIP', title: 'DeviceIP', width: '100px', id: 'DeviceIP' },
{ field: 'Producer', title: 'Producer', width: '80px', id: 'Producer' },//editor: ProductNameDropDownEditor,
{ field: 'Model', title: 'Model', width: '220px', id: 'Model' },
// { field: 'DeviceType', title: 'DeviceType', width: '100px', id: 'DeviceType', editor: deviceTypesList },
{ field: 'Description', title: 'Description', width: '220px' },
{ field: 'Username', title: 'Username', width: '120px' },
{ field: 'Password', title: 'Password', width: '100px' },
{ field: 'PublicIP', title: 'PublicIP', width: '120px', id: 'PublicIP' },
{ field: 'TurbineId', title: 'TurbineId', width: '120px', id: 'TurbineId', hidden: true },
{ field: 'device_id', title: 'device_id', width: '120px', id: 'deviceid', hidden: true },
// { field: 'ModelProducer', title: 'Producer/Model', id: 'ModelProducer', hidden: true, editor: modelPro },
{
command: ["edit"], title: " "
}
],
editable: "popup",
});
}
})
}
});
//This Part Is For The AUTOCOMPLETE textbox
$(document).ready(function () {
var value = document.getElementById('autocomplete').value;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("List_Turbine","AdminTool")",
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({ "name": value ,}),
data: {},
success: function (result) {
$("#autocomplete").kendoAutoComplete({
dataSource: result,
dataTextField: "Text",
// filter: "contains"
});
}
})
});

kendo ui grid sortable and crud is not working

I have followed this tutorial and brought up the sorting to work but now the crud operation is not working.
If i remove the grid sortable code then the crud is working, but no sort.
I have no idea where i am making mistake to make both sort and crud to work
THis is the code i have
$(document).ready(function () {
function dataSource_change(e) {
var data = this.data();
console.log(data.length); // displays "77"
}
var dataSource = new kendo.data.DataSource({
//pageSize: 20,
transport:{
read:{
url: function() {
return "/makes"},
dataType: "json",
cache: false
},
update: {
url: function (make) {
console.log(make)
return "/makes/"+ make.models[0].id
},
type: "PUT",
dataType: "json",
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token',jQuery('meta[name="csrf-token"]').attr("content")); }
},
destroy: {
url: function (make) {
return "/makes/"+ make.models[0].id
},
type: "DELETE",
dataType: "json"
},
create: {
url: "/makes",
type: "POST",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
console.log(options)
return{"make": options.models[0]};
}
else{
return {"make":options};
}
}
},
batch: true,
schema: {
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } },
}
}
}
});
dataSource.bind("change", dataSource_change);
dataSource.fetch();
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: false,
height: 550,
toolbar: [{name: "create", text: "Add New Make"}],
columns: [
{ field:"name",title:"Makes" },
{ command: ["edit", "destroy"], title: "Action", width: "250px" }],
editable: "inline"
}).data("kendoGrid");
grid.table.kendoSortable({
filter: ">tbody >tr",
hint: $.noop,
cursor: "move",
placeholder: function(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
},
container: "#grid tbody",
change: function(e) {
console.log(grid)
var skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
var updated_order = []
$('tbody tr').each(function(i){
updated_order.push({ name: $(this).children('td:first').text(), position: i+1 });
});
controller_name = $('#controller_name').val();
$.ajax({
type: "PUT",
url: '/sort',
data: { order: updated_order, controller_name: controller_name }
});
grid.dataSource.remove(dataItem);
grid.dataSource.insert(e.newIndex, dataItem);
}
});
});

How to add new tags in select2?

I am trying to get the tags from my api. Everything works fine but I cant able to add new tags. Here is what i tried:
$(function(){
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
$('#s2id_id_add-places').select2({
multiple: true,
tags: [],
tokenSeparators: [",", " "],
width: "200px",
ajax: {
placeholder: "Click to enter who",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://example.com/api/v3/places/",
dataType: "json",
contentType: "application/json",
processData: true,
quietMillis: 50,
data: function(term) {
return {
term: term
};
},
results: function(data) {
var results = [];
if(data.objects.length > 0) {
for (i=0; i<data.objects.length; i++) {
results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
}
}
return {
results: results
};
},
});
});
By using the above code, I can only get the tags but I cant able to add the new tags. how can i add the new tags?
Please help
$("#e11_2").select2({
createSearchChoice: function(term, data) {
if ($(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
You have to create a function like createSearchChoice, that returns a object with 'id' and 'text'. In other case, if you return undefined the option not will be created.

kendo ui grid loading indicator not showing

I am using kendo grid in my html page and every thing working perfectly but one issue i am facing when page loads and i send request to get data it takes 1 or 2 seconds meanwhile grid should show loading indicator as we can see in demo . This is what i am doing
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: api/getdata,
dataType: 'json',
cache: false,
headers: { 'ccode': compCode },
async: false,
data: '?&tableName=' + table + '&userId=' + userId + '&fromDate=' + dateFrom + '&toDate=' + dateto + '&isSearchForClient=' + true,
success: function (result) {
var data = [];
if (result) {
result = result.replace(/&/g, "'");
var jsonResult = JSON.parse(JSON.parse(result));
for (var i = 0; i < jsonResult.length; i++) {
data.push({ Log: jsonResult[i]["Log"], TransactionId: jsonResult[i]["TransactionId"] });
}
var grid = $("#logs").kendoGrid({
dataSource: {
data: data,
schema: {
model: {
fields: {
TransactionId: { type: "string" },
Log: { type: "string" }
}
}
},
pageSize: 10
},
height: 405,
scrollable: true,
detailInit: detailInit,
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
pageable: {
input: true,
numeric: false
},
columns: [
{ field: 'Log', title: "Audit Logs", encoded: true }]
});
//grid.dataSource.read();
}
}
});

Categories

Resources