Saving the whole EditorGrid with a single Ajax request - javascript

I would like to save an ExtJS (3.3.1) editorgrid with a single Ajax request.
I've created an editorgrid, based on an ArrayStore.
var store = new Ext.data.ArrayStore({
data: arrayData,
fields: [ 'id', 'qty', 'idService', 'idSubscription',
'description', 'vat', 'amount' ]
});
[...]
var grid = {
xtype: 'editorgrid',
store: store,
view: gridView,
colModel: colModel,
selModel: selModel,
stripeRows: true,
tbar: tbar,
autoHeight: true,
width: 872,
clicksToEdit: 1
};
I've created a Save button with the following handler:
app.inv.saveButtonHandler = function () {
var myForm = Ext.getCmp("formHeader").getForm();
if (!myForm.isValid()) {
Ext.MessageBox.alert('Form Not Submitted',
'Please complete the form and try again.');
return;
}
myForm.el.mask('Please wait', 'x-mask-loading');
Ext.Ajax.request({
params: {
idCustomer: myForm.findField("idCustomer").getValue(),
issueDate: myForm.findField("issueDate").getValue(),
documentType: myForm.findField("documentType").getValue(),
documentNumber: myForm.findField("documentNumber").getValue()
},
url: 'save-sales-document-action',
method: 'POST',
success: function (response, request) {
myForm.el.unmask();
Ext.MessageBox.alert('Success', 'Returned: ' + response.responseText);
},
failure: function (response, request) {
myForm.el.unmask();
Ext.MessageBox.alert('Failed', 'Returned: ' + response.responseText);
}
});
};
In other words, I can send form elements with a simple value, but I don't know how to send the whole data grid. I would like to send the whole data grid with a single Ajax request.
I've already used before the cell-by-cell saving method, but in this case I would prefer to save the whole grid in one go. I don't need help for the server-side part, that I will do in Java, only for the client-side JavaScript.
Can someone help? Thanks!

After a night sleep and still no answers, I made further tries and I can answer my own question. I will leave the question open anyway, in case someone knows a better way.
To solve my problem, I added the property "storeId: 'gridStore'" to the ArrayStore, so I could locate the store later with Ext.StoreMgr.lookup(), then, at saving time, I proceed to re-build an Array record by record in the following way:
var gridData = new Array();
Ext.storeMgr.lookup('gridStore').each(function (record) {
gridData.push(record.data);
});
The essential part is that I don't get the whole Record, but only the data field of it.
After I've an array with the data, the easy part is add it to the params of Ajax.request:
params: {
...
gridData: Ext.encode(gridData)
},
This finally works. All the data is encoded in a single field. Of course on the server it will have to be decoded.

Related

How to get data from xml by using URL

I have a grid where I am loading the data from the data store. Bu using some url. Code is something like that.
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
method: 'GET',
url: SomeURL
}),
remoteSort:true,
method: 'GET',
baseParams: {start: 0, limit: 25},
sortInfo:{
field: 'UPDATEDON',
direction: 'DESC'
},
reader: new Ext.data.XmlReader({
totalProperty:'#Total',
record: 'ITEM'
}, [ {name:'name',type:'string', mapping:'#name',SortType:"asUCString"},
{name:'value', mapping:'#value'}
]),
grid:this,
listener : {
load:function(){
}
}
This is loading correctly. No problem in grid. I need to access grid data at some other place in my code. so for that I am call
`var xyz = new MyGrid({val:1,newval:2});`
val and newVal are the two para for grid. But I am not getting store and store value here. Is there anyway I can get store here or get the xml value by using the same url again.
You can set in your store autoLoad: true - if it is already binded/set with this new Grid.
Or just say xyz.store.reload();
Reloads the store using the last options passed to the load method.
You can get the data form xyz.store.
How to get the information from a store depends on you and what you have there stored. You can use 'find', 'findBy', 'each' and so on (senscha doc extjs V3.4)

update parameters variable on change.search using bootgrid with structured-filter

I am using https://github.com/evoluteur/structured-filter and http://www.jquery-bootgrid.com/ to create an advanced search through ajax/php.
Initially the code works and returns the data from the php file, but when trying to use structured-filter to pass $_GET variables to the php file through the use of jquery-bootgrid I am struggling.
No matter what I try, the url it is posting to has no $_GET variables, I have tried $("#grid-data").bootgrid("reload"); but nothing changes.
It appears the params variable is just not updating.
Here is my jquery script in full:
<script type="text/javascript">
$(document).ready(function() {
$("#myFilter").structFilter({
fields: [{
type: "text",
id: "gamertag",
label: "Gamertag"
}, {
type: "text",
id: "name",
label: "Team Name"
}, {
type: "number",
id: "wagePerMatch",
label: "Wage Per Match"
}, {
type: "number",
id: "gamesRemaining",
label: "Contract Games Remanining"
}, {
type: "boolean",
id: "transferListed",
label: "Transfer Listed"
}
]
});
var params = "";
$("#myFilter").on("change.search", function(event) {
var params = $("#myFilter").structFilter("valUrl");
$("#grid-data").bootgrid("reload");
console.log(params); // works, returns params
});
$("#grid-data").bootgrid({
ajax: true,
url: function() {
return "/api/search.php?" + params; // params never updates?
}
});
});
</script>
Is there a way to update params in .bootgrid when it changes in $("#myFilter").on("change.search" as right now its only sending requests to /api/search.php? (missing the parameters)
Now i don't have to much reputation, i am unable to add comment on this,
Please check this below URL, hope this will help you
http://www.jquery-bootgrid.com/Documentation#events
if you are looking for append the rows in existing grid so you can use "append" as given in URL or if you want to update the whole table you can destory the table and re-create a "bootgrid" object with binding with the respective DOM id's

Populate a Select2 Tag input field with data from an AJAX request using X-editable jQuery library

I am in desperate need of some help from JavaScript experts. I have spent the last 7 hours trying hundreds of combinations of code to get a basic Tag selection input field to work with the library x-editable and select2.
I am building a Project Management app which is going to have Project Task data shown in a popup Modal Div. In the Task Modal, all Task fields will be editable with in-line edit-in-place capability using AJAX.
I am using:
the jQuery edit in place library called X-Editable - http://vitalets.github.io/x-editable/
The drop down selection jQuery library Select2 - https://select2.github.io/
The jQuery MockAjax library to allow simulating AJAX request responses. https://github.com/jakerella/jquery-mockjax
I have setup a basic JSFiddle demo to experiment with just for this StackOverflow question. I don't have the thousands of lines of code from my actual application , however I do have majority of the 3rd part libraries that are being used included into the page. THe reason is to make sure that none of them are interfering with the results.
JSFiddle Demo: http://jsfiddle.net/jasondavis/Lusbqfhs/
The Goal:
Setup X-editable and Select2 on a Field to allow users to select and enter in Tags for a Project Task.
Fetch available Tag records from a backend server which will return a JSON response with Tag ID number and Tag Name and use this data to populate the Selection2 input field to allow a user to select multiple Tags.
Allow user to also type in a NEW tag and it will post and save the new Tags to the backend as well!
When tags are selected and the save button is clicked, it will save the list of selected Tags bu ID number back to a database.
Problems:
Now I have tried hundreds of variations of options and code combinations from my research in the past 7 hours. I cannot seem to get this basic functionality to work and majority of the examples I have found do not seem to work correctly anymore!
On this demo page for the library x-editable http://vitalets.github.io/x-editable/demo-plain.html?c=inline near the bottom of the examples in the table where it says Select2 (tags mode) that functionality is what I need! I just need it to load the available tags from an AJAX request and all the docs claim it can do this with no problem at all!
This is the Documentation section from X-Editable for Select2 fields - http://vitalets.github.io/x-editable/docs.html#select2
It also links to the Select2 documentation and claims that all the Options in Select2 can be set and used as well located here - https://select2.github.io/options.html
I use MockAjax library to simulate an AJAX response in pages like JSFiddle for testing. In my JSFiddle demo here http://jsfiddle.net/jasondavis/Lusbqfhs/ I have 2 MockAjax responses set up....
$.mockjax({
url: '/getTaskTags',
responseTime: 400,
response: function(settings) {
this.responseText = [
{id: 1, text: 'user1'},
{id: 2, text: 'user2'},
{id: 3, text: 'user3'},
{id: 4, text: 'user4'},
{id: 5, text: 'user5'},
{id: 6, text: 'user6'}
];
}
});
$.mockjax({
url: '/getTaskTagById',
responseTime: 400,
response: function(settings) {
this.responseText = [
{id: 1, text: 'user1'},
{id: 2, text: 'user2'},
{id: 3, text: 'user3'},
{id: 4, text: 'user4'},
{id: 5, text: 'user5'},
{id: 6, text: 'user6'}
];
}
});
They both are supposed to return a Mock JSON string for my Selection list to be populated with.
Here is my code for the demo...
$(function(){
//remote source (advanced)
$('#task-tags').editable({
mode: 'inline',
select2: {
width: '192px',
placeholder: 'Select Country',
allowClear: true,
//minimumInputLength: 1,
id: function (item) {
return item.CountryId;
},
// Get list of Tags from AJAX request
ajax: {
url: '/getTaskTags',
type: 'post',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
formatResult: function (item) {
return item.TagName;
},
formatSelection: function (item) {
return item.TagName;
},
initSelection: function (element, callback) {
return $.get('/getTaskTagById', {
query: element.val()
}, function (data) {
callback(data);
});
}
}
});
});
Now in the demo when you click the field to select Tags, it just keeps "loading" and never gets a result. Looking at the Console, it seems my MockAjax request is not working, however the 2nd one is working so I am not sure what is wrong with my AJAX request?
I could really use some help if someone can help to get this to work I would be very greatful, I have spent my whole night without sleep and am not even any closer to a working solution! Please help me!
Thank you
X-Editable uses Select2 3.5.2 which doesn't use jQuery.ajax() directly. It has its own ajax function and calls jQuery.ajax() like that:
transport = options.transport || $.fn.select2.ajaxDefaults.transport
...
handler = transport.call(self, params);
That's why $.mockjax({url: '/getTaskTags'... does not work.
To get it work you need to create your own transport function, something like that:
var transport = function (queryParams) {
return $.ajax(queryParams);
};
and set the transport option:
ajax: {
url: '/getTaskTags',
=> transport: transport,
type: 'post',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},

Save nested form data back to server in ExtJS

I have a Model that contains an association to another Model. I am able to display the nested data into a form by using the mapping attribute on the field. Example:
Ext.define('Example.model.Request', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: Ext.data.Types.NUMBER,
useNull: false
}
{
name: 'plan_surveyor',
mapping: 'plan.surveyor',
type: Ext.data.Types.STRING
}
],
associations: [
{type: 'hasOne', associationKey: 'plan', getterName:'getPlan', model: 'Specs.model.Plan'}
],
proxy: {
type: 'direct',
api: {
read: requestController.load,
update: requestController.update,
},
reader: {
type: 'json',
root: 'records'
},
writer: {
type: 'json',
writeAllFields: true,
nameProperty: 'mapping'
}
}
});
Using this method, I can display the plan.surveyor value in the form by reference plan_surveyor. I call Form.loadRecord(model) to pull the data from the model into the form.
However, now that I'm trying to send the data back to the server, I get the error:
Error performing action. Please report the following: "Unrecognized field "plan.surveyor"
I am attempting to save to the server by first calling Form.updateRecord(model), then model.save(). Is there a way to have the Writer understand that 'plan.surveyor' is not a property name but instead to properly handle nesting?
Am I doing this the right way to start with, or should I just be handling the setting of the form data and loading back into the model in a more manual fashion? It seems that nested data is not all that well supported in general - any recommendations?
Ext.define('Example.model.Request', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: Ext.data.Types.NUMBER,
useNull: false
}
{
name: 'plan_surveyor',
mapping: 'plan.surveyor',//change to 'plan_surveyor'
type: Ext.data.Types.STRING
}
],
change that show in comment ,because data index is given in above format because ur give ur format thata time that is not dataindex it's a column or extjs preparatory ,so please change that may it's work well
it's not work u will send hole code

ExtJS4 Changing data store parameters

If I have a data store on a grid like so:
store = Ext.create('Ext.data.Store', {
fields: [{
name: 'id'
}, {
name: 'filename'
}
// other fields here ...
],
proxy: {
type: 'ajax',
url: 'http://myniftyurl.com/blah',
simpleSortMode: true,
reader: {
type: 'json',
totalProperty: 'total',
root: 'result'
},
extraParams: {
'limit': Ext.get('itemsPerPage').getValue(),
'to': Ext.get('to_date').getValue()
// other params
}
},
model: 'Page',
remoteFilter: true,
remoteSort: true
});
The 'limit' and 'to' value will change based on user input, therein lies the problem. The data store keeps using the original parameters instead of the new inputs. How can I fix this?
Thanks in advance!
I normally load my grids manually by executing the store.load() in the controller.
That way prior to it I can change the store's params like so:
//getForm() retrieves the Ext.basic.Form (from Ext.panel.Form)
var params = this.getForm().getValues();
//Write over
grid.getStore().getProxy().extraParams = params;
//load
grid.getStore().load();
I'm using buffered grids which required a decent amount of rework to get completely working in 4.0.7. But that should work for you.
Another options is to use a beforeload listener but I'm not sure if changing the extraParams by then will do anything. You may be able to modified the Ext.data.Operation object that gets passed to the event handler?
Let me know how that works out for you.
Good luck!

Categories