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');
});
Related
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
This question already has answers here:
Jquery Ajax Posting JSON to webservice
(5 answers)
Closed 8 years ago.
Problem: When sending data to MongoDB via AJAX, the subarry name points[0][x] is becoming a single string: "points[0][x]". How do I prevent the key from becoming a single string?
I added an object into MongoDB using Ajax post like this:
if(errorCount === 0) {
var newDesign = {
filename: 'designs/documents-desktop.jpg',
title: 'Tester',
slug: 'tester',
pos: '1',
points: [
{
x: '0.40',
y: '0.211',
title: 'test',
content: 'Blank for now'
},
{
x: '0.295',
y: '0.090',
title: 'Another Test',
content: 'Blank for now again'
}
]
}
$.ajax({
type: "POST",
data: newDesign,
url: "/data/add-design",
dataType: 'JSON',
}).done(function(response) {
if(response.msg === '') {
} else {
alert("ERROR: " + response.msg);
}
});
}
Then I use getJSON to GET this, and use console.log to output this.points[0][x]:
$.getJSON('/data', function(data) {
$.each(data, function() {
console.log(this.points[0][x])
});
});
But it doesn't work and I get this error:
Uncaught TypeError: Cannot read property '0' of undefined
You can see that all of the data is there when your console.log the entire object, but each subarray key is a single string:
{"_id":"54bcb74584a4c8bd05e3d772","filename":"designs/documents-desktop.jpg","title":"Tester","slug":"tester","pos":"1","points[0][x]":"0.40","points[0][y]":"0.211","points[0][title]":"test","points[0][content]":"Blank for now","points[1][x]":"0.295","points[1][y]":"0.090","points[1][title]":"Another Test","points[1][content]":"Blank for now again"}
You can also see in a mongo terminal that points[0][x] is becoming a single string:
db.filelist.find().pretty();
{
"_id" : ObjectId("54bcc85384a4c8bd05e3d777"),
"filename" : "designs/documents-desktop.jpg",
"title" : "Tester",
"slug" : "tester",
"pos" : "1",
"points[0][x]" : "0.40",
"points[0][y]" : "0.211",
"points[0][title]" : "test",
"points[0][content]" : "Blank for now",
"points[1][x]" : "0.295",
"points[1][y]" : "0.090",
"points[1][title]" : "Another Test",
"points[1][content]" : "Blank for now again"
}
Is there something I'm missing here? I don't seemingly have any mistakes in the server side with NodeJS and Express. What could be the problem?
Thanks to #adeneo and #NeilLunn we solved the problem. The AJAX request was specifying the contentType as "json", when what it really needed to be is "application/json; charset=utf-8". Now the subarray key is being included correctly in MongoDB:
$.ajax({
type: "POST",
data: JSON.stringify(newDesign),
url: "/data/add-design",
contentType: 'application/json; charset=utf-8',
}).done(function(response) {
if(response.msg === '') {
} else {
alert("ERROR: " + response.msg);
}
});
I have the following Select2 configuration.
$scope.select2Options = {
simple_tags: false,
placeholder : "Search for a language",
multiple : true,
contentType: "application/json; charset=utf-8",
minimumInputLength : 3,
ajax : {
url : "/bignibou/utils/findLanguagesByLanguageStartingWith.json",
dataType : 'json',
data : function(term) {
return {
language : term
};
},
results : function(data, page) {
return {
results :
data.map(function(item) {
return {
id : item.id,
text : item.description
};
}
)};
}
}
};
This allows me to populate the select2 control properly.
However, an issue occurs when I use Ajax in order to post the whole form containing the tags (amongst other): the json array sent to the server contains objects with two properties named id and text whereas the server would require id and description.
see snippet from my json:
"languages":[{"id":46,"text":"Français"},{"id":1,"text":"Anglais"}]
Does select2 allow for changing the name of the text to something else?
Changing my js to the following sorted the issue:
function format(item) { return item.description; };
$scope.select2Options = {
simple_tags: false,
placeholder : "Search for a language",
multiple : true,
contentType: "application/json; charset=utf-8",
minimumInputLength : 3,
data:{ text: "description" },
formatSelection: format,
formatResult: format,
ajax : {
url : "/bignibou/utils/findLanguagesByLanguageStartingWith.json",
dataType : 'json',
data : function(term) {
return {
language : term
};
},
results : function(data, page) {
return {
results :
data.map(function(item) {
return {
id : item.id,
description : item.description
};
}
)};
}
}
};
Notice: one has to use the Select2 top level attribute data.
Here's the bare minium of the configuration neccesary to use a custom id and text properties on ui-select2
$scope.clients: {
data: [{ ClientId: 1, ClientName: "ClientA" }, { ClientId: 2, ClientName: "ClientB" }],
id: 'ClientId',
formatSelection: function (item) { return item.ClientName; },
formatResult: function (item) { return item.ClientName; }
}
Select2 requires that the text that should be displayed for an option is stored in the text property. You can map this property from any existing property using the following JavaScript:
var data = $.map(yourArrayData, function (obj) {
obj.text = obj.text || obj.name; // replace name with the property used for the text
obj.id = obj.id || obj.pk; // replace pk with your identifier
return obj;
});
Documentation
I'm trying to override the default parameter name for limitParam in proxy for the Store. I want to make a JSONP call to http://search.twitter.com/search.json?q=kathmandu&rpp=2 but instead of setting rpp directly I want to map it to limitParam and set it's value. But it's not setting through limitParam. The reason I'm doing is the parameter keys store sends (sort, dir, etc) do not match the parameters on the server side (which I've no control over). Thanks in advance.
Ext.require('Ext.grid.View');
Ext.require('Ext.util.Point');
Ext.application({
name: 'HelloExt',
launch: function() {
/*Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [
{
title: 'Hello Ext',
html : 'Hello! Welcome to Ext JS.'
}
]
});*/
console.log('ok1');
Ext.define('Video', {
extend: 'Ext.data.Model',
fields: ['from_user', 'from_user_id']
});
var myStore2 = Ext.create('Ext.data.Store', {
model: 'Video',
storeId : 'restfulStore',
proxy: {
type: 'jsonp',
url : 'http://search.twitter.com/search.json?q=kathmandu',
reader: {
type: 'json',
//root: 'data.items'
root: 'results'
},
limitParam: 'rpp',
pageParam: 'page'
},
listeners: {
load: function(store, records) {
Ext.each(records, function(rec) {
console.log(rec.get('from_user'));
});
}
},
sorters: [{
property: 'from_user',
direction: 'DESC'
}, {
property: 'from_user_id',
direction: 'ASC'
}],
//autoLoad: true,
remoteSort: true
});
var p = myStore2.getProxy();
p.limitParam = 2;
myStore2.load();
console.log('loads anyway??? loaded the store ...');
Ext.create('Ext.grid.Panel', {
title: 'Restful Grid',
store: Ext.data.StoreManager.lookup('restfulStore'),
columns: [
{header: "From User", width: 200, sortable: true, dataIndex: 'from_user'},
{header: "From User ID", width: 200, sortable: true, dataIndex: 'from_user_id'}
],
height: 400,
width: 400,
renderTo: Ext.getBody()
});
console.log('store loaded!!');
}
});
Your proxy configuration is fine for what you want to do. The problem is in the way you load the store. You should not change limitParam which is really the config option for the name of the param. To affect the number of results, use the limit option of the load method, that you can also configure in the store with the pageSize option.
So, remove this:
var p = myStore2.getProxy();
p.limitParam = 2;
And instead, use the limit option when loading the store:
myStore2.load({
limit: 2
});
Alternatively, you can set this in the store config with the pageSize option:
Ext.create('Ext.data.Store', {
// ...
pageSize: 2
,autoLoad: true
});
You can mix both by setting a default with pageSize, and changing it at loading time with limit.
As a side note, the tweeter API doesn't seem to support sorting, so your sorters configuration won't have any effect on the returned results. You should switch remoteSort to false to have the returned results sorted on the client side according to your configuration.
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.