Good day, i'm new to webix and codeigniter, i wanna ask if after getting the json from controller the format is like {End_date: "2019-07-31", value: "2019-07-31"} in console log, how to display on webix text?
function GetEndDate() {
return $.ajax('<?php echo base_url(); ?
>index.php/date/dateController/GetEndDate/' + Id);
}
webix.ready(function(){
$.when(GetEndDate()).done(function(EndDates){
EndDate = EndDates[0];
rendersformSection();
});
});
function rendersformSection(){
{view:'text', id:'Final_date', name:'Final_date', labelAlign:
'right',label:'Final Date', labelWidth:200,
suggest: {
filter: function (item, value) {
if (item.value.toString().toLowerCase().indexOf(value.toLowerCase()) >= 0)
return true;
return false;
},
body: {
data: EndDate,
datatype: "json",
template: function(obj){
return obj.End_date;
}
}
},
on: {
onBeforeShow: function () {
var texts = [];
EndDate.forEach(function (obj) {
texts.push(obj.value);
});
}
}
webix.ui(rendersformSection);
}
I expect when the page load. the final date will show the date get from the function GetEndDate().
Related
We are working with a 3rd party grid (telerik kendo) that has paging/sorting/filtering built in. It will send the requests in a certain way when making the GET call and I'm trying to determine if there is a way to translate these requests to AutoQuery friendly requests.
Query string params
Sort Pattern:
sort[{0}][field] and sort[{0}][dir]
Filtering:
filter[filters][{0}][field]
filter[filters][{0}][operator]
filter[filters][{0}][value]
So this which is populated in the querystring:
filter[filters][0][field]
filter[filters][0][operator]
filter[filters][0][value]
would need to be translated to.
FieldName=1 // filter[filters][0][field]+filter[filters][0][operator]+filter[filters][0][value] in a nutshell (not exactly true)
Should I manipulate the querystring object in a plugin by removing the filters (or just adding the ones I need) ? Is there a better option here?
I'm not sure there is a clean way to do this on the kendo side either.
I will explain the two routes I'm going down, I hope to see a better answer.
First, I tried to modify the querystring in a request filter, but could not. I ended up having to run the autoqueries manually by getting the params and modifying them before calling AutoQuery.Execute. Something like this:
var requestparams = Request.ToAutoQueryParams();
var q = AutoQueryDb.CreateQuery(requestobject, requestparams);
AutoQueryDb.Execute(requestobject, q);
I wish there was a more global way to do this. The extension method just loops over all the querystring params and adds the ones that I need.
After doing the above work, I wasn't very happy with the result so I investigated doing it differently and ended up with the following:
Register the Kendo grid filter operations to their equivalent Service Stack auto query ones:
var aq = new AutoQueryFeature { MaxLimit = 100, EnableAutoQueryViewer=true };
aq.ImplicitConventions.Add("%neq", aq.ImplicitConventions["%NotEqualTo"]);
aq.ImplicitConventions.Add("%eq", "{Field} = {Value}");
Next, on the grid's read operation, we need to reformat the the querystring:
read: {
url: "/api/stuff?format=json&isGrid=true",
data: function (options) {
if (options.sort && options.sort.length > 0) {
options.OrderBy = (options.sort[0].dir == "desc" ? "-" : "") + options.sort[0].field;
}
if (options.filter && options.filter.filters.length > 0) {
for (var i = 0; i < options.filter.filters.length; i++) {
var f = options.filter.filters[i];
console.log(f);
options[f.field + f.operator] = f.value;
}
}
}
Now, the grid will send the operations in a Autoquery friendly manner.
I created an AutoQueryDataSource ts class that you may or may not find useful.
It's usage is along the lines of:
this.gridDataSource = AutoQueryKendoDataSource.getDefaultInstance<dtos.QueryDbSubclass, dtos.ListDefinition>('/api/autoQueryRoute', { orderByDesc: 'createdOn' });
export default class AutoQueryKendoDataSource<queryT extends dtos.QueryDb_1<T>, T> extends kendo.data.DataSource {
private constructor(options: kendo.data.DataSourceOptions = {}, public route?: string, public request?: queryT) {
super(options)
}
defer: ng.IDeferred<any>;
static exportToExcel(columns: kendo.ui.GridColumn[], dataSource: kendo.data.DataSource, filename: string) {
let rows = [{ cells: columns.map(d => { return { value: d.field }; }) }];
dataSource.fetch(function () {
var data = this.data();
for (var i = 0; i < data.length; i++) {
//push single row for every record
rows.push({
cells: _.map(columns, d => { return { value: data[i][d.field] } })
})
}
var workbook = new kendo.ooxml.Workbook({
sheets: [
{
columns: _.map(columns, d => { return { autoWidth: true } }),
// Title of the sheet
title: filename,
// Rows of the sheet
rows: rows
}
]
});
//save the file as Excel file with extension xlsx
kendo.saveAs({ dataURI: workbook.toDataURL(), fileName: filename });
})
}
static getDefaultInstance<queryT extends dtos.QueryDb_1<T>, T>(route: string, request: queryT, $q?: ng.IQService, model?: any) {
let sortInfo: {
orderBy?: string,
orderByDesc?: string,
skip?: number
} = {
};
let opts = {
transport: {
read: {
url: route,
dataType: 'json',
data: request
},
parameterMap: (data, type) => {
if (type == 'read') {
if (data.sort) {
data.sort.forEach((s: any) => {
if (s.field.indexOf('.') > -1) {
var arr = _.split(s.field, '.')
s.field = arr[arr.length - 1];
}
})
}//for autoquery to work, need only field names not entity names.
sortInfo = {
orderByDesc: _.join(_.map(_.filter(data.sort, (s: any) => s.dir == 'desc'), 'field'), ','),
orderBy: _.join(_.map(_.filter(data.sort, (s: any) => s.dir == 'asc'), 'field'), ','),
skip: 0
}
if (data.page)
sortInfo.skip = (data.page - 1) * data.pageSize,
_.extend(data, request);
//override sorting if done via grid
if (sortInfo.orderByDesc) {
(<any>data).orderByDesc = sortInfo.orderByDesc;
(<any>data).orderBy = null;
}
if (sortInfo.orderBy) {
(<any>data).orderBy = sortInfo.orderBy;
(<any>data).orderByDesc = null;
}
(<any>data).skip = sortInfo.skip;
return data;
}
return data;
},
},
requestStart: (e: kendo.data.DataSourceRequestStartEvent) => {
let ds = <AutoQueryKendoDataSource<queryT, T>>e.sender;
if ($q)
ds.defer = $q.defer();
},
requestEnd: (e: kendo.data.DataSourceRequestEndEvent) => {
new DatesToStringsService().convert(e.response);
let ds = <AutoQueryKendoDataSource<queryT, T>>e.sender;
if (ds.defer)
ds.defer.resolve();
},
schema: {
data: (response: dtos.QueryResponse<T>) => {
return response.results;
},
type: 'json',
total: 'total',
model: model
},
pageSize: request.take || 40,
page: 1,
serverPaging: true,
serverSorting: true
}
let ds = new AutoQueryKendoDataSource<queryT, T>(opts, route, request);
return ds;
}
}
im working on ASP.NET MVC 4 project. well i already insert data into a SQL Server database using jQuery using a post method in .
Now im trying to insert data into 2 tables using the same view, my problem is that i can't passing multiple POST parameters to Web API Controller Method. here is my js function and my controller code, ill apreciate your help
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient},
success: function (data) {
if(data==0) {
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1) {
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
Controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient: dataClient},
success: function (data) {
if(data==0){
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1){
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
//controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
you did not add dataClient: dataClient in ajax.
so please add this.
Hope this will help you.
Im using Parse REST API + AngularJS and Im trying to be able to get more than 1000 items per query. I try to develop a recursive function and concatenate each query until I get all the data. My problem is that I am not able to concatenate the JSON objects successfully. Here is what I have:
$scope.getAllItems = function(queryLimit, querySkip, query) {
$http({method : 'GET',
url : 'https://api.parse.com/1/classes/myClass',
headers: { 'X-Parse-Application-Id':'XXX','X-Parse-REST-API-Key':'YYY'},
params: {limit:queryLimit, skip:querySkip},
}).success(function(data, status) {
query.concat(data.results);
if(query.lenth == queryLimit) {
querySkip += queryLimit;
queryLimit += 100;
$scope.getAllItems(queryLimit, querySkip, query);
} else {
$scope.clients = query;
}
})
.error(function(data, status) {
alert("Error");
});
};
var myQuery = angular.toJson([]); //Am I creating an empty JSON Obj?
$scope.getAllItems(100,0, myQuery);
Is there any better solution to achieve this?
There may be better, more concise ideas available, but this is what I worked out for myself.
In my service ...
fetch : function(page, perpage) {
var query = // build the query
// the whole answer to your question might be this line:
query.limit(perpage).skip(page*perpage);
return query.find();
},
fetchCount : function() {
var query = // build the same query as above
return query.count();
},
In the controller...
$scope.page = 0; // the page we're on
$scope.perpage = 30; // objects per page
MyService.fetchCount().then(function(count) {
var pagesCount = Math.ceil(count / $scope.perpage);
$scope.pages = [];
// pages is just an array of ints to give the view page number buttons
for (var i=0; i<pagesCount; i++) { $scope.pages.push(i); }
fetch();
});
function fetch() {
return MyService.fetch($scope.page, $scope.perpage)).then(function(results) {
$scope.results = results;
});
}
// functions to do page navigation
$scope.nextPage = function() {
$scope.page += 1;
fetch();
};
$scope.prevPage = function() {
$scope.page -= 1;
fetch();
};
$scope.selectedPage = function(p) {
$scope.page = p;
fetch();
};
Then paging buttons and results in my view (bootstrap.css)...
<ul class="pagination">
<li ng-click="prevPage()" ng-class="(page==0)? 'disabled' : ''"><a>«</a></li>
<li ng-repeat="p in pages" ng-click="selectedPage(p)" ng-class="(page==$index)? 'active' : ''"><a>{{p+1}}</a></li>
<li ng-click="nextPage()" ng-class="(page>=pages.length-1)? 'disabled' : ''"><a>»</a></li>
</ul>
<ul><li ng-repeat="result in results"> ... </li></ul>
I fixed my recursive function and now its working. Here it is:
$scope.getAllItems = function(queryLimit, querySkip, query, first) {
$http({method : 'GET',
url : 'https://api.parse.com/1/classes/myClass',
headers: { 'X-Parse-Application-Id':'XXX','X-Parse-REST-API-Key':'YYY'},
params: {limit:queryLimit, skip:querySkip},
}).success(function(data, status) {
if(first) {
query = data.results;
first = !first;
if(query.length == queryLimit) {
querySkip += queryLimit;
$scope.getAllItems(queryLimit, querySkip, query, first);
} else {
$scope.clients = query;
}
} else {
var newQ = data.results;
for (var i = 0 ; i < newQ.length ; i++) {
query.push(newQ[i]);
}
if(query.length == queryLimit + querySkip) {
querySkip += queryLimit;
$scope.getAllItems(queryLimit, querySkip, query, first);
} else {
$scope.clients = query;
}
}
})
.error(function(data, status) {
alert("Error");
});
};
Simply pushed each element to my empty array, also I was mutating queryLimit instead of querySkip in order to iterate through all the elements.
i want to return JSON from my controller and get it in my view .this is my code, when i debug it . goes to my controller and get value but in my j query code nothing happen .when i debug my j query code by firebug it dos not run the function(data). what is wrong in my code ?i want get object of part-booklet from server. its a row of data and add this row to my Telerik mvc grid .thanks in advance
its my contoroller code:
#region dynamic_add_row_to_grid
private PartBooklet GetPartBooklet( int sparepart ) {
return _PartBookletService.GetList().Where(m => m.SparePartCode == sparepart).FirstOrDefault();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetItems( int sparepart ) {
var PartbookletList = this.GetPartBooklet(sparepart);
return Json(PartbookletList, JsonRequestBehavior.AllowGet);
}
#endregion
and its jquery code:
$("#btnadd").button().click( function () {
alert("button");
var sparepartcode = $("#SparePartCode").val();
alert( sparepartcode );
$.getJSON("../Shared/GetItems", { sparepart: sparepartcode }, function( data ) {
alert( data.val );
alert("PartbookletList");
var grid = $('#InvoiceItemGrid').data('tGrid');
grid.dataBind( data );
}).error( function () {
alert("JSON call failed");
});
$( function () {
$.ajaxSetup({
error: function (jqXHR, exception) {
if ( jqXHR.status === 0 ) {
alert('Not connect.\n Verify Network.');
} else if ( jqXHR.status == 404 ) {
alert('Requested page not found. [404]');
} else if ( jqXHR.status == 500 ) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror' ) {
alert('Requested JSON parse failed.');
} else if ( exception === 'timeout' ) {
alert('Time out error.');
} else if ( exception === 'abort' ) {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
});
$("#btnadd").button().click( function () {
//alert("button");
var sparepartcode = $("#SparePartCode").val();
$.ajax({
url: "/Shared/GetItem?sparepart=" + sparepartcode,
type: 'GET',
success: function(a, b, data) {
//alert( data.val );
alert("PartbookletList");
var grid = $('#InvoiceItemGrid').data('tGrid');
grid.dataBind( data );
},
error: function(jqXHR, textStatus, errorThrown) {
alert("JSON call failed");
},
// other options and setup ...
});
});
Note that in a successful ajax request, it's the 3rd parameter that contains the actual data you need.
I am trying to follow this example
and I have the following in JSP page
(getData.jsp)
Department t = new Department ();
String query = request.getParameter("q");
List<String> tenders = t.getDepartments(query);
Iterator<String> iterator = tenders.iterator();
while(iterator.hasNext()) {
String deptName= (String)iterator.next();
String depto = (String)iterator.next();
out.println(deptName);
}
How can I use the above to use in Jquery autcomplete? When I tried there was no output coming.
My Jquery autoComplete code
<script>
$(function() {
$( "#dept" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getData.jsp",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.<??>, function( item ) {
return {
label: item.name + (item.<??> ? ", " + item.<??> : "") + ", " + item.<??>,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
alert(ui.item.label);
}
});
});
</script>
Is your response in JSON format?
Here's what I do when I use Jquery UI Autocomplete:
Create a class whose parameters are the ones you will use when you say item.name
public string Pam1{ get; set; }
public string Pam2{ get; set; }
public string Pam3{ get; set; }
public SomeResponse(string SomePam)
{
// Pam1 = ???
// Pam2 = ???
// Pam3 = ???
}
In your handler:
context.Response.ContentType = "application/json";
string query = (string)context.Request.QueryString["query"];
var json = new JavaScriptSerializer();
context.Response.Write(
json.Serialize(new SomeResponse(query))
);
context.Response.Flush();
context.Response.End();
EDIT
The javascript (Here is an example where the user can choose more than one option, separated by coma. If you don't want that, remove it.) txt_autocomplete is the class of the TextBox.
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".txt_autocomplete")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function (request, response) {
$.getJSON("handlers/autocomplete.ashx?query=" + extractLast(request.term), {
term: extractLast(request.term)
}, response);
},
search: function () {
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.Pam1);
terms.push("");
this.value = terms.join(", ");
console.log("Pam1 is :" + ui.item.Pam1 + " Pam2 is: " + ui.item.Pam2 + " Pam 3 is : " + ui.item.Pam3);
return false;
}
});
});