I am new to ExtJS and I am trying to implement a combo box and 'Save' button that will save the "boxStatus" for all of the records selected in my grid (there is a little checkbox column for selecting records, and a combo box for the status). I have tried with the following ajax call:
saveBulkBoxComments : function(){
var formObj = this.getPositionPanel().getForm();
var fieldValues = formObj.getFieldValues();
Ext.Ajax.request({
url: SAVE_BULK_BOX_COMMENTS_URL,
method: 'POST',
params: {
positionDate: this.parentRecordData.data.positionDate,
groupIds: this.parentRecordData.data.groupId,
boxStatus: fieldValues.boxStatus,
csrComment: fieldValues.csrComment
},
success : function(response) {
//how do I update box status for all records selected?
this.loadPositions();
},
scope: this
});
}
Here is the Java:
return getReturnValue(new Runnable() {
public void run() {
String groupIdList[] = groupIds.split(",");
String user = mercuryUserScreenNameGetter.getValue(request);
Date date = Utils.parseDate(positionDate, DATE_FORMAT);
Stream.of(groupIdList)
.forEach(groupId ->
positionsDataMediator.addBoxAnnotation(date,user, groupId, csrComment, boxStatus));
}
});
I am not really sure how to post all of the boxStatus for all of the records selected. Would I have to write a method that iterates over all of the records when I hit Save? That seems wrong...Thanks for the help.
After some fiddling, I got it working. The trick was to iterate over each groupID, for all of the selected records...this way I was able to update the boxStatus for each of those records at once:
saveBulkBoxComments : function(){
grid = this.getPositionPanel();
var store = grid.getStore();
formObj = this.getBoxCommentsFormPanel().getForm();
var fieldValues = formObj.getFieldValues();
var value='';
selectedRecords = grid.getSelectionModel().getSelection();
Ext.each(selectedRecords, function(item) {
value +=item.get('groupId') +',';
}
);
Ext.Ajax.request({
url: SAVE_BULK_BOX_COMMENTS_URL,
method: 'POST',
params: {
groupIds :value,
positionDate: this.parentRecordData.data.positionDate,
boxStatus: fieldValues.boxStatus,
csrComment: fieldValues.csrComment
},
success: function(result, action, response) {
var jsonData = Ext.decode(result.responseText);
var jsonRecords = jsonData.records;
Ext.getCmp('boxCommentsWindow').close();
this.loadPositions();
},
scope: this
});
}
});
Related
I have a dynamic table and i want to send in controller by ajax. I have code ajax like this :
$(".save").click(function(e){
var items = new Array();
$("#list-item tr.item").each(function () {
$this = $(this)
var ref_item_id = $this.find("#ref_item_id").val();
var ref_pic_id = $this.find("#ref_pic_id").val();
var price= $this.find("#price").val();
var qty= $this.find("#qty").val();
items.push({ ref_item_id : ref_item_id, ref_pic_id : ref_pic_id, price: price, qty : qty});
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<?php echo base_url("transac/save")?>',
dataType: "json",
data: JSON.stringify({'items': items }),
success: function (data) {
var obj = $.parseJSON(data);
alert(obj.lenth);
},
error: function (result) { alert(result); }
});
})
now, how get data in controller and save in table database. My Controller like this :
public function penjualan_save(){
$items = $this->input->post("items");
// next code ???
}
I hope you can help me. Thanks
first thing, your don't need JSON.stringify({'items': items }), just use:
data: {'items': items },
and in your controller, just create a model and pass your post data into it, for example:
public function penjualan_save(){
$items = $this->input->post("items");
$this->load->model('model_name');
$this->model_name->insert($items);
}
then you need to define a function for your model, like this:
public function insert($data)
{
// if you didn't call database library in autoload.php
$this->load->database();
$this->db->insert_batch('mytable', $data);
}
I have a page with three form fields (2 textbox, 1 dropdown), a submit button and a 'refresh' link. I want to be able to click the link and pass two form textbox values to a controller action, and get a list of values to populate the dropdown box. I do not want to submit the form at this stage.
At the moment, I have managed to call the controller action from the link click, but I cannot pass the two form field values in for some reason. Also, the return JSON just takes me to a new page instead of populating my dropdown list. Any pointers would be great as I am new to javascript and MVC. My code is below;
Controller
public ActionResult Find(AddressFormViewModel model)
{
...
var temp = new List<OptionModel>();
temp.Add(new OptionModel {Id = item.Id, Value = item.desc});
return Json(temp, JsonRequestBehavior.AllowGet);
}
HTML
#Html.TextBoxFor(x => Model.HouseNameInput, new { id = "HouseNameInput" })
#Html.TextBoxFor(x => Model.PostCodeInput, new { id = "PostCodeInput" })
#Html.ActionLink("Find","Find", "Address", new { houseInput = Model.HouseNameInput, postcodeInput = Model.PostCodeInput }, new { htmlAttributes = new { #class = "Find" } })
#Html.DropDownListFor(x => Model.AddressOption, Enumerable.Empty<System.Web.Mvc.SelectListItem>(), "-- Loading Values --", new {id = "AddressOptions"})
And lastly, my Javascript method which is retrieving the data from the controller action but not populating the dropdown list (it displays the results in a new page). It is also not successfully sending the form values to the controller action.
$(function () {
$('.Find').click(function (evt) {
$.ajax({
type: 'POST',
url: '#Url.Action("Find","AddressFormSurface")',
cache: false,
async: true,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
houseNameInput: $("#HouseNameInput").value,
postCodeInput: $("#PostCodeInput").value
},
success: function (data) {
if (data.exists) {
var ddl = $('#AddressOptions');
ddl.empty();
data.each(function () {
$(document.createElement('option'))
.attr('value', this.Id)
.text(this.Value)
.appendTo(ddl);
});
}
},
error: function (req) {
}
});
// we make sure to cancel the default action of the link
// because we will be sending an AJAX call
return false;
});
});
You have a number of errors in your script which will cause it to fail.
You specify contentType: "application/json; charset=utf-8", but do
not stringify the data (the option should be removed)
You need to use .val() (not .value) to get the values of the
inputs
The data you receiving does not contain a property named exists so
the if block where you append the options will never be hit
In addition it is unnecessary to generate your link using #Html.ActionLink() (your adding route values based on the initial values of the model). Instead just create it manually
Find
and change the script to
var ddl = $('#AddressOptions'); // cache it
$('#find').click(function () { // change selector
$.ajax({
type: 'GET', // its a GET, not a POST
url: '#Url.Action("Find","AddressFormSurface")', // see side note below
cache: false,
async: true,
dataType: "json",
data: {
houseNameInput: $("#HouseNameInput").val(),
postCodeInput: $("#PostCodeInput").val()
},
success: function (data) {
if (!data) {
// oops
return;
}
ddl.empty();
$.each(data, function(index, item) {
$(document.createElement('option'))
.attr('value', item.Id)
.text(item.Value)
.appendTo(ddl);
// or ddl.append($('<option></option>').text(item.Value).val(item.Id));
});
},
error: function (req) {
....
}
}
});
Side note: Also check the name of the controller. Your Html.ActionLink() suggests its AddressController but your script is calling AddressFormSurfaceController
I am returning array of strings from controller to ajax call. trying to set to textbox those values. in textbox it is not populating. but I can see data in success method.
[HttpGet]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult GetWorkNamesAutoPoplate(string companyName)
{
...
var newKeys = companyNameslst.Select(x => new string[] { x }).ToArray();
var json = JsonConvert.SerializeObject(newKeys);
return Json(json, JsonRequestBehavior.AllowGet);
}
JS
$(document).on('change', '[name="FindCompanyName"]', function () {
$('[name="FindCompanyName"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "GetWorkNamesAutoPoplate",
type: "GET",
dataType: "json",
data: { companyName: $('[name="FindCompanyName"]').val() },
success: function (data) {
alert(JSON.stringify(data));
response($.map(data, function(item) {
console.log(item);
return {
value: item
}
}));
}
});
},
messages: {
noResults: "", results: ""
}
});
});
alert(JSON.stringify(data)); display like this.
How to populate this data in textbox
The return type of your json is an array of arrays, i think you should return it as an array
var newKeys = companyNameslst.ToArray();
also, your data are serialized twice,
one from line,
var json = JsonConvert.SerializeObject(newKeys);
and second time from JsonResult action filter
return Json(json, JsonRequestBehavior.AllowGet);
sending json data like,
return Json(newKeys, JsonRequestBehavior.AllowGet);
instead of
var json = JsonConvert.SerializeObject(newKeys);
return Json(json, JsonRequestBehavior.AllowGet);
should work.
hope this helps.
This may resolve your issue :
success: function (data) {
alert(JSON.stringify(data));
if (data != null) {
response(data.d);
}
}
Also this link might help you to get some information :How to use source: function()... and AJAX in JQuery UI autocomplete
i have been trying to fix this, what i want to do is:
I have a datasource who gets data from server, when i go to server, i get the list of items, then i have to search the item i have to select (This item could be in any page), after i have the item and the page where the item is located (assuming each page has 30 items), then i call LINQ expression to skip the required ammount of data and take 30. Finally i return this list to the client side.
When data arrives to client i need to "auto-select" the selected item and change the page to locate the user in the right page where the selected item is located. I have the new page, skip, selected value and everything in the client side again.
What do you suggest to me to change the page into the kendo grid datasource without call a new refresh and go to the server again?
This is how the datasource looks like:
return new kendo.data.DataSource({
serverPaging: true,
transport: {
read: {
url: URLController.Current().getURL('MyURL'),
contentType: 'application/json',
accepts: 'application/json',
type: 'POST'
},
parameterMap: function(data, type) {
if (data) {
return JSON.stringify(
{
data: jsonData,
pageSize: data.pageSize,
skip: data.skip,
take: data.take
});
}
}
},
schema: {
data: function (data) {
var dropDownData = JSON.parse(data);
gridElement.attr('data-model', JSON.stringify({ data: data }));
return dropDownData.Data;
},
total: function (data) {
var dropDownData = JSON.parse(data);
return dropDownData.total;
},
model: {
id: 'ID'
}
},
pageable: true,
pageSize: 30,
error: function(e) {
alert('Error ' + e);
}
});
When the grid data is bounded i have to change the page to current page number and then select the current item.
grid.one('dataBound', function (e) {
var currentGridElement = this.element;
var currentModel = currentGridElement.attr('data-model');
var currentJsonData = parseDropDownDataJSONString(currentModel).data;
var gridDataSource = this.dataSource;
var selection = gridDataSource.get(currentJsonData.selectedValue);
if (selection != undefined) {
var row = currentGridElement.find('tbody>tr[data-uid=' + selection.uid + ']');
if (row != undefined) {
currentGridElement.attr('data-closeByChange', false);
gridDataSource.page(currentJsonData.pageNumber);
this.select(row);
dexonDropDownGrid.combobox().text(selection.DISPLAY);
}
}
var aaaa = 0;
});
This is how my databound event listener looks like, when i try to set the page it calls again the server and i got more delay to load the right data.
Is there any way to solve this?
Thanks
Have the same problem.
There is how I fix that(not the best solution ever, but it works):
var forcedPageChange = false;
var cachedResult;
var dataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
if (forcedPageChange) { // prevent data request after manual page change
forcedPageChange = false;
options.success(cachedResult);
cachedResult = null;
return;
}
gridDataProvider.getData() // promise of data
.then(function (result) {
// check if current page number was changed
if ($scope.gridConfig.dataSource.page() !== result.pageNumber ||
$scope.gridConfig.dataSource.pageSize() !== result.rowsPerPage) {
cachedResult = _.clone(result);
forcedPageChange = true;
options.page = result.pageNumber;
options.pageSize = result.rowsPerPage;
$scope.gridConfig.dataSource.query(options);
}
options.success(result);
}, function () {
options.error();
});
}
},
schema: {
data: function (response) {
return response.items;
},
total: function (response) {
return response.totalCount;
}
},
//...
serverPaging: true,
serverSorting: true,
serverFiltering: true
});
I found that dataSource.page(newPageNumber) doesn't work in this situation. It just drop page number to 1.
This solution works, but I still have a bug with missing sorting icon after dataSource.query(options)...
I have a scenario that I'm attempting to apply knockout to with some problems. Basically I have this sort of ui
Add (create a new Select Box duo with delete button)
Select Box (options = Json from ajax request)
Select Box (options = Json from ajax request with param from 1st select)
Delete
Select Box
Select Box
Delete
etc
Each row I regard as another Widget in the array so my knockout for simplicity
var ViewModel = function (widgets) {
var self = this;
this.widgets= ko.observableArray(widgets);
this.subWidgets= ko.observableArray();
this.mySelections = ko.observableArray();
this.selectedWidget.subscribe(function (name) {
if (name != null) {
$.ajax({
url: '#Url.Action("AddSubWidgetsByName")',
data: { name: name },
type: 'GET',
async: false,
contentType: 'application/json',
success: function (result) {
self.subWidgets(result);
}
});
}
} .bind(this));
self.addWidget = function (widget) {
self.mySelections.push({
??? profit
});
};
}
var viewiewModel = new ViewModel();
ko.applyBindings(viewiewModel);
$.ajax({
url: '#Url.Action("AddFund")',
type: 'GET',
async: false,
contentType: 'application/json',
success: function (result) {
viewModel.widgets(result);
}
});
<select id="widgets"
data-bind='
options: widgets,
optionsValue : "Name",
optionsText: "Name",
optionsCaption: "[Please select a widgets]"'
value: selectedWidget,
>
Can I dynamically create a select for each widget and relate the subwidget selection to an item in mySelections array? I can't use the value binding for selectedWidget in quite this way as all dropdowns are bound together in this manner. I need to make them independant - any ideas on how to go about that?
Cheers!
One way of doing this is to make each widget its own viewmodel (note, this is from jsFiddle, so the ajax is done to work with their echo API, which requires POST):
var Widget = function(){
var self = this;
self.selectedWidget = ko.observable('');
self.subWidgets = ko.observableArray([]);
self.selectedSubWidget = ko.observable('');
this.selectedWidget.subscribe(function (name) {
if (name != null) {
$.ajax({
url:"/echo/json/",
data: {
json: $.toJSON(
[Math.floor(Math.random()*11),
Math.floor(Math.random()*11),
Math.floor(Math.random()*11)]
),
delay: 1
},
type:"POST",
success:function(response)
{
self.subWidgets(response);
}
});
}
});
};
You could then easily track sub-selections and additions with a simple viewmodel. Here is the complete fiddle.