For examplpe I am fetching the record through Json and in success function am storing the return data in localstorage to use
Output Json like
[{"1":"Core"},{"2":"Moderate"},{"3":"Remote"}]
It's returning as expected
but I can't populate the data in drop down, if i hard coded the same json it's working. Thanks in advance please help me to resolve.
$.ajax({
url: 'http://test.com',
//type: 'POST',
//data :Editorcontent,
success: function (data) {
let fieldes = JSON.parse(data)
localStorage.setItem('one',fieldes)
},
error: function () {
alert(url);
}
});
var selected = localStorage.getItem('one');
//selected = [{"1":"Core"},{"2":"Moderate"},{"3":"Remote"}]
//selected = selected.replace('\'',"'");
console.log(selected);
var editor = {
ajax: '',
ajaxFiles: '',
struct: {
buttons: ['top', 'bottom'] // buttons
},
fields: [
{
label: "Branch Name",
name: "DefaultBranchID",
values: selected,
type: 'select'
},
{
label: "Country:",
name: "CountryID",
type: 'multiselect',
attrs: [
{'pattern': '^[A-Za-z0-9_]+$'}
]
},
"selected" is the variable am assigning
OutPut for Branch Nam Drop down :-O/p
Related
I have a java map. I converted it to json string and I obtain something like this :
{"NEW ZEALAND":"111111111111111","CHAD":"1","MOROCCO":"111","LATVIA":"11"}
Now I want to use it in a store and then a chart like the following code but it's not working. I have no error just no display.
var obj = Ext.Ajax.request({
url: App.rootPath + '/controller/home/dashboard/test.json',
method:'GET',
success: function(response) {
return Ext.JSON.decode(response.responseText);
}
});
var store2 = Ext.create('Ext.data.Store', {
model: 'PopulationPoint',
data: obj
});
Ext.create('Ext.chart.Chart', {
renderTo: 'infos2',
width: 500,
height: 300,
store: store2,
series: [
{
type: 'pie',
field: 'population',
label: {
field: 'state',
display: 'rotate',
font: '12px Arial'
}
}
]
});
The AJAX request is asynchronous. As such, the obj variable used to initialize your data won't contain your data yet.
One option is to create the store2 variable and create the chart directly in the success callback of the AJAX request.
A cleaner option would be to configure the store with a proxy to load the url, and in the callback create the chart.
EDIT
The JSON response does not contain the fields that are declared in your model (sent in the comments). Update the JSON to return a properly formatted model and the chart should work as seen in this fiddle. The JSON should look something like
[
{
"state" : "New Zealand",
"population" : 111111111
},
{
"state" : "Chad",
"population" : 1
}
]
I have the following code. When fetching the value selected, it works fine. But if I try put the selected value in any condition, it falters. the code crashes.
var onAcctMgrSelect = function (e) {
// access the selected item via e.item (jQuery object)
ddAMList = $("#ddAM").data("kendoDropDownList");
if (ddAMList.value() == "0")
$("#btnSearch").attr("class", "k-button k-state-disabled");
else
$("#btnSearch").attr("class", "k-button");
///alert(ddAMList.text());
checkValidData();
};
DropDownlist Code is as below:
function loadAccountManagers() {
$("#ddAM").kendoDropDownList({
change: onAcctMgrSelect,
dataTextField: "AcctMgrFullName",
dataValueField: "Id",
dataSource: {
schema: {
data: "d", // svc services return JSON in the following format { "d": <result> }. Specify how to get the result.
total: "count",
model: { // define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
Id: { validation: { required: true }, type: "int" },
AcctMgrFullName: { type: "string", validation: { required: true} }
}
}
},
transport: {
read: {
url: "../services/Prospects.svc/GetAccountManagers", //specify the URL which data should return the records. This is the Read method of the Products.svc service.
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "GET" //use HTTP POST request as the default GET is not allowed for svc
}
}
}
});
I'm basically trying to disable the submit button if the first item is selected (which is a blank item in my case with a value of '0').
Am I going wrong anywhere? Please help!
I have a question about extjs 4.
Below is my storeMsg
var storeMsg = this.getMessageStore();
storeMsg.load({
scope: this,
autoLoad: true,
params:{
read_conditions: Ext.JSON.encode({
"employee_rid": '7976',
"year" : '2013', //etos
"kind_holiday_rid" : '1',
"request_days" : '5'
})
},
callback: function(records, operation, success) {
// do something after the load finishes
console.log(records[0].get('remain'));
console.log(records[0].get('messages'));
}
});
and i take a json response like as
{"total":1,"success":true,"data":[{"status":"true","messages":"\u03a3\u03c9\u03c3\u03c4\u03cc \u03b1\u03af\u03c4\u03b7\u03bc\u03b1 \u03ac\u03b4\u03b5\u03b9\u03b1\u03c2","remain":"25"}]}
I want to take the field status from json (ex true) outside from storeMsg.load();
For example
var vstatus = Ext.StoreMgr.lookup(storeMsg).data.items[0].data.status
but i take message this vstatus is undefined
I have changed my variable (vstatus) of code :
var vstatus = Ext.StoreMgr.lookup(storeMsg).getProxy().getReader();
and I am taking and object like as
className "Ext.data.reader.Json"
and it has some attributes. An attribute is
jsonData
data
remain 25
status true
message "Is correct"
total 1
success true
and I give in
var vstatus = Ext.StoreMgr.lookup(storeMsg).getProxy().getReader().jsonData;
and I take this message (undefined).
Do you have any idea how take the value from jsonData.data.status = true;
tnx
and the fully code about store , proxy and reader is below
Ext.define('MHR.store.Message',{
extend : 'Ext.data.Store',
model : 'MHR.model.Message',
storeId : 'Message',
autoLoad : true,
proxy : {
type: 'ajax',
api: {
read : 'php/crud.php?action=check'
},
actionMethods: {
read : 'POST',
},
reader: {
type: 'json',
root: 'data',
rootProperty: 'data',
successProperty: 'success',
messageProperty: 'message'
},
extraParams : {
'read_conditions': ''
}
}
});
try with:
storeMsg.each(function(record) {
var status = record.get('status');
});
I have same problem as Daniel had in this topic, but his solution doesn't work for me:
http://www.kendoui.com/forums/ui/grid/kendo-ui-grid-inserts-updates-create-duplicate-records.aspx#-jhxqRrNAUGsTFJaC-Ojwg
So use-case. Users adds 2 new records one after another:
Presses "Add new record" button of a grid
Fills the fields (name="Alex", amount=10, comment="first").
Record one is ready. Press 'Save'. (data goes to controller and than to Database)
User see one record in a grid
Press "Add new record" button again
Fills fields (name="Bob", amount=20, comment = "second").
Record one is ready. Press 'Save'. Data goes to controller and than to Database.
In this moment something happens and grid send Ajax request again with record one data to controller.
User updates grid and see three records
"Alex | 10 | first" (duplicated record) ID = 1
"Bob | 20 | second" ID = 2
"Alex | 10 | first" ID = 1
They recommend to return an ID for correct binding\update of data source with new record.
And I return it (new ID from database comes in response with bouns entity)! and this doesn't help.
Only if I add first record and refresh page with F5 and after that add second record everything is ok. But if add another one, the third records - problems appears again
Code in controller:
[HttpPost]
public JsonResult Create(BonusDto bonusDto)
{
BonusAggregate bonus;
if (bonusDto.Amount <= 0)
throw new ArgumentOutOfRangeException("Amount should be more than 0");
if (bonusDto.EmployeeId <= 0)
throw new ArgumentNullException("You should specify an existing employee");
using (var dbContext = new DatabaseContext())
{
BonusesRepository = new BonusesRepository(dbContext);
var employeeRepository = new EmployeesRepository(dbContext);
bonus = new BonusFactory(employeeRepository).Create(bonusDto);
BonusesRepository.Save(bonus);
}
HttpContext.Response.StatusCode = (int)HttpStatusCode.Created;
return Json(bonus); // try to return ID after bonus was saved
}
UI Code
// creates bonuses grid control
$("#bonusesGrid").kendoGrid({
dataSource: bonusesDataSource,
toolbar: ["create"],
editable: "inline",
columns: [
"BonusId",
"EmployeeId",
{
field: "EmployeeLastName",
editor: employeeAutocompletingEditor,
template: "#=EmployeeLastName#"
},
"Amount",
{
field: "Comment",
titel: "Comment",
editor: textareaEditor,
filterable: {
operators: {
number: {
contains: "Contains"
}
}
}
},
{
command: ["edit"],
title: " "
}
],
save: function(e) {
if (newValueEmployeeId !== undefined &&
newValueEmployeeLastName !== undefined &&
newValueEmployeeLastName !== "") {
setNewValueEmployeeIdAndLastName(newValueEmployeeId, newValueEmployeeLastName);
gridDataSource.model.EmployeeId = newValueEmployeeId; // it's a hack to bind model and autocomplete control
gridDataSource.model.EmployeeLastName = newValueEmployeeLastName;
} else {
gridDataSource.model.EmployeeId = currentValueEmployeeId;
gridDataSource.model.EmployeeLastName = currentValueEmployeeLastName;
}
},
edit: function(e) {
setCurrentValueEmployeeIdAndLastName(e.model.EmployeeId, e.model.EmployeeLastName);
},
cancel: function(e) {
setCurrentValueEmployeeIdAndLastName(e.model.EmployeeId, e.model.EmployeeLastName);
}
});
Bonus data source:
// bind json result from /Bonuses/GetPagedJsonBonuses
var bonusesDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("GetPagedJsonBonuses", "Bonuses")",
type : "GET",
contentType: "application/json",
dataType: "json",
cache: false
},
create: {
url: "#Url.Action("Create", "Bonuses")",
dataType: "json",
type: "POST"
},
parameterMap: function(options, operation) {
if (operation === "update" || operation === "create") {
// correct format for conversion
var d = new Date(options.Date);
options.Date = kendo.toString(d, dateFormat);
// updates the BonusDTO.EmployeeId with selected value
if (newValueEmployeeId !== undefined)
options.EmployeeId = newValueEmployeeId;
}
if(operation === "read") {
options.filter = setFormattedFilterDate(options.filter);
}
return options;
}
},
pageSize: 15,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
error: showErrorMessage,
schema: {
data: "Data", // PagedResponse.Data
total: "TotalCount", // PagedResponse.TotalCount
model: {
id: "BonusId", // Data
fields: {
EmployeeId: { type: "number" },
EmployeeLastName: {
type: "string",
editable: true,
nulable: false,
validation: { required: {message: "Employee's last name is required"}}
},
Date: {
type: "date",
editable: true,
nullable: false,
validation: {
required: { message: "Date is required to be set" }
}
},
Amount: {
type: "number",
editable: true,
nullable: false,
defaultValue: 1,
validation: {
required: { message: "Amount is required to be set" }
}
},
Comment: { type: "string", editable: true }
} // fields
} // model
}// schema
});
I haven't seen this problem in my code. I do however have a "complete" event handler on my create and update events that refreshed the grid - it may help you:
dataSource: {
type: "jsonp",
transport: {
read: UrlBase + "getAll",
update: {
url: UrlBase + "Update",
dataType: "jsonp",
complete: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
}
},
create: {
url: UrlBase + "create",
dataType: "jsonp",
complete: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
}
},
destroy: {
url: UrlBase + "destroy",
dataType: "jsonp",
complete: function (e) {
$("#grid").data("kendoGrid").dataSource.read();
}
}
},
...
Yes, hamed is correct. Your "create" action result passes in the object from your model that is to be saved to your database. Have the INSERT in your data access layer return the newly created key ("ID") in the database. Use this key to now set the "ID" field on your model that's passed in to the action result and then passed back to the view as JSON. Now the grid should know it's just created this record and does not need to do anything more with it. Otherwise, the model object returns with the "ID" field set to 0 so the grid thinks it still needs to add this record.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Grid_Create([DataSourceRequest] DataSourceRequest request, MyObject obj)
{
if (obj != null && ModelState.IsValid)
{
obj.Id = _myService.Create(obj);
}
return Json(new[] { obj }.ToDataSourceResult(request, ModelState));
}
This error occur when you did not pass Primary key to view in read action.
Regards
An alternative to Quinton Bernhardt's complete event: bind the dataSource.read() to the kendo sync event.
I'm using kendo's C# MVC's html helpers which don't expose the sync event, so I had to modify it after setting up the grid.
On window load:
var grid = $("#GridName").data("kendoGrid");
grid.dataSource.bind("sync", function () {
$("#GridName").data("kendoGrid").dataSource.read();
});
The sync event fires after the save request has been completed. The dataSource.read() gets the latest from the server, including the id that was set server side.
I had a similar issue, did various trials but fixed with the following trial
Jquery
create: {
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "../../ajax/ajaxGv.aspx/addstaff"
},
parameterMap: function (options, operation) {
if (operation == "create" && options.models) {
return JSON.stringify({ "oStaff": options.models });
}
VB.Net
'Adding Staff
<System.Web.Services.WebMethod()> _
Public Shared Sub addStaff(ByVal oStaff As Object)
Dim strJson As String = JsonConvert.SerializeObject(oStaff)
Dim lstStaff As List(Of Staff) = JsonConvert.DeserializeObject(Of List(Of Staff))(strJson)
Dim db As New LiveB2cDataContext
Try
db.Staff.InsertAllOnSubmit(lstStaff)
Next
db.SubmitChanges()
'Fix is that you need to return the objects you have added in the database back as json to kendo
strJson = JsonConvert.SerializeObject(lstStaff, Formatting.None)
WriteJson(strJson) ' Returning the objects added as json back to Kendo
Catch ex As Exception
ErrorLog(ex)
End Try
End Sub
Public Shared Sub WriteJson(strJson As String)
Try
HttpContext.Current.Response.Write(strJson)
HttpContext.Current.Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
HttpContext.Current.Response.SuppressContent = True
Catch ex As Exception
ErrorLog(ex)
End Try
End Sub
Fix is that you need to return the objects you have added in the database back as json to kendo
I'm not sure if this is part of your issue, but in your DataSource's schema model you specify that the ID is the field named "BonusId", but that field isn't specified in the array of fields.
I was having a simular issue.
I fixed it but making sure the id in the model is referring to a field:-
model: {
id: "Id",
fields: {
Id: { editable: false, type: "number" },
AnotherName: { editable: true, type: "string" },
AnotherId: { editable: true, type: "number" }
}
}
This may not solve the asker's problem, but hopefully might help someone with the same issue.
For us, this problem was being caused by errors being returned in JSON. Some required properties didn't have a value, but weren't related to the data we were displaying in the grid. Giving those properties a default value in the grid solved the issue.
You can view the JSON that's being returned by using Fiddler Web Debugging Tools.
I am using Bootstrap typeahead with an ajax function, and want to know what is the correct Json result format, to return an Id and a descripcion.
I need the Id to bind the typeahead selected element with a mvc3 model.
This is the code:
[Html]
<input id="myTypeahead" class='ajax-typeahead' type="text" data-link="myUrl" data-provide="typeahead" />
[Javascript]
$('#myTypeahead').typeahead({
source: function (query, process) {
return $.ajax({
url: $('#myTypeahead').data('link'),
type: 'post',
data: { query: query },
dataType: 'json',
success: function (jsonResult) {
return typeof jsonResult == 'undefined' ? false : process(jsonResult);
}
});
}
});
This works properly when I return a simple list of strings, for example:
{item1, item2, item3}
But I want to return a list with Id, for example:
{
{Id: 1, value: item1},
{Id: 2, value: item2},
{Id: 3, value: item3}
}
How to process this result in the ajax "success: function()"?
That is very easy with jquery Autocomplete, because I can return a Json Object list.
[jquery Autocomplete process data example]
...
success: function (data) {
response($.map(data, function (item) {
return { label: item.Id, value: item.Value, id: item.Id, data: item };
})
...
But that doesn't work with boostrap Typeahead.
Can anyone help me?
Thanks.
I try for two days and finally I could it working.
Bootstrap Typeahead doesn't support an array of objects as a result by default, only an array of string. Because "matcher", "sorter", "updater" and "highlighter" functions expect strings as parameter.
Instead, "Bootstrap" supports customizable "matcher", "sorter", "updater" and "highlighter" functions. So we can rewrite those functions in Typeahead options.
II used Json format, and bound the Id to a hidden html input.
The code:
$('#myTypeahead').typeahead({
source: function (query, process) {
return $.ajax({
url: $('#myTypeahead').data('link'),
type: 'post',
data: { query: query },
dataType: 'json',
success: function (result) {
var resultList = result.map(function (item) {
var aItem = { id: item.Id, name: item.Name };
return JSON.stringify(aItem);
});
return process(resultList);
}
});
},
matcher: function (obj) {
var item = JSON.parse(obj);
return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
},
sorter: function (items) {
var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
while (aItem = items.shift()) {
var item = JSON.parse(aItem);
if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
else caseInsensitive.push(JSON.stringify(item));
}
return beginswith.concat(caseSensitive, caseInsensitive)
},
highlighter: function (obj) {
var item = JSON.parse(obj);
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
return '<strong>' + match + '</strong>'
})
},
updater: function (obj) {
var item = JSON.parse(obj);
$('#IdControl').attr('value', item.id);
return item.name;
}
});
Note: I saw #EralpB`s comment "Is this still the best way to accomplish this task?"
Yes, #Gonzalo solution works, but it seems strange (like crutch,especially after using jQuery-Autocomplete) - it should work "from box".Better is to use this - Bootstrap-3-Typeahead. It supports an array of objects as result: format - [{id: .. ,name:...},...,{id: .. ,name:...}]. Example for OP`s issue:
....
source: function (query, process) {
return $.ajax({
......
success: function (result) {
var resultList = [];
$.map(result,function (Id,value) {
var aItem = { id: Id, name: value};
resultList.push(aItem);
});
return process(resultList);
}
});
},