Array (json) not passing into jqGrid's editoptions parameters - javascript

I've been trying to pass an array from a global variable (codata) to an option array of editoptions (jqGrid). My code stands as follows:
--------- countries_list.php throws the following json array -----------
["ABU","AD","AE","AF" .... "ZA","ZM","ZW"]
--------- PHP script with jqGrid Code ----------
jQuery(document).ready(function(){
var codata = new Array();
$.getJSON('countries_list.php', function(list){
$.each(list, function(val) {
codata.push("'"+val+"'");
# --- Here alert() displays 'codata' with all the elements ---
});
});
$("#datatable").jqGrid({
......
// some code until colMode specs
......
{ name:'guco',
index:'guco',
edittype:'select',
width:90,
editable: true,
editoptions: {
formatter:'select',
value: codata # --- array is not passed, it comes empty ---
},
sortable: true,
resizable: false
},
.....
--------- PHP script with jqGrid Code ----------
Any hint how to get this fixed?, thanx in advance.
Mario Benitez.-

Thanx a lot to all you guys, I learnt a lot with your contributions. Problem was fixed as follows:
(reading about) I found that getjson works an 'async mode' (I'm a jQuery newbie) and the code to fix the problem was:
jQuery(document).ready(function(){
var codata = (function () {
var list = null;
$.ajax({
'async': false,
'global': false,
'url': 'countries_list.php',
'dataType': 'json',
'success': function (data) {
list = data;
}
});
return list;
})();
$("#datatable").jqGrid({
... jqGrid settings ...
colModel: [
....
{ name:'guco',
index:'guco',
edittype:'select',
width:90,
editable: true,
editoptions: {
value: codata
},
sortable: true,
resizable: false
},
....
Thanx a lot once again, I hope this helps to someone else.
Mario Benitez.

From what i see your php script is passing valid js array, not json object. The most logic thing to do is to call jqGrid inside the ajax callback assigning $("#datatable").jqGrid({ ... editoptions: { value: list } ... });

I would recommend you to use dataUrl together with buildSelect instead of value of the editoptions. You can find the corresponding code example of buildSelect in the "UPDATED" part of the answer.

I tried both ways and the Answer given in Olegs links helped. Using the buildSelect param allows full control of the value. When I used value method it assigned simple integer values of 0 - n. You can also assign your own CSS classes in this paradigm too. +1 for buildSelect/dataurl.

Related

Trying to fill select box with Inputpicker plugin and JQuery

$('#src_prodline').inputpicker({ calling the plugin function
fields:['id','code','description'],
fieldText : 'description',
fieldValue : 'code',
headShow: true,
filterOpen: true,
$.ajax({
url: 'item_action.php', //Calling the function
type:"POST",
data: {
btn_action:'src_prodline' //Set item_id and variable se
}
});
});
In my console I got this error:
SintaxError: missing : after property id
What's wrong with that and how can I fix it???
UPDATE:
Creating a new php file it's working
$('#src_prodline').inputpicker({
fields:['id','code','desc'],
fieldText : 'description',
fieldValue : 'code',
pagination: true,
limit: 5,
headShow: true,
filterOpen: true,
url: 'item_1.php',
pageCurrent: 1
});
BUT unfortunately this is not what I want because I got a PHP page with different functions and I call one of theme with a $_POST['btn_action']
Example:
if ($_POST['btn_action']=='src_prodline'){
...........
}
So, my problem is that I don't have idea how can I send this variable at PHP page without error.
-->LOOK the code above update<--
Do you have any idea how can I solve this?
UPDATE Ver. 2.0
I fixed it adding the variable in the web address but I hate to do that:
url: 'item_action.php?r=src_prodline'
Now, it's working but if somebody has a better solution please let me know it.

JQGrid : restoring toolbar values and operators from filter

I am using JQGrid (version 5.3.0) to display values from a dynamic table (that I don't know the column number and columns names in advance). I retreive the columns schema from an ajax call to the server, as well as a filter that needs to be applied to the grid, and create the JQGrid from there.
The problem I am facing is that I find no way to repopulate the filter toolbar correctly from the filter that is passed to the table.
The code is the following :
$.ajax({
url: {url to get columns and filter},
type: 'POST',
postData: { productID: 98 }
success: function (result) {
if (result) {
$('#grid').jqGrid({
url: {url to get data},
datatype: 'json',
search: true,
postData: { productID: 98, filters: result.filter },
myType: 'GET',
colModel: result.columns,
jsonReader: {
root: 'Data',
page: 'Page',
total: 'Total',
records: 'PageSize'
},
pager: $('#gridpager'),
rowNum: 25,
gridview: false,
afterInsertRow: function (rowid, rowdata, rowelem) {
var color = rowelem.Color;
if (color != 'white') {
$("tr.jqgrow#" + rowid).addClass("color-" + color);
}
},
}).filterToolbar({
groupOp: 'AND',
defaultSearch: "cn",
searchOnEnter: true,
searchOperators: true,
stringResult: true,
});
}
}
});
Here is an example of the Columns model:
[
{
"name":"DESCRIPTION",
"label":"Description",
"searchoptions":
{
"sopt": ["bw","cn","nc","ew","eq","ne","in"],
"attr":{"class":"glyphicon glyphicon-filter"}
}
},
{
"name":"SKU_CODE",
"label":"SKU Code",
"searchoptions":
{
"sopt":["bw","cn","nc","ew","eq","ne","in"],
"attr":{"class":"glyphicon glyphicon-filter"}
}
},
{...}
]
And here is the filter :
"{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"DESCRIPTION\",\"op\":\"bw\",\"data\":\"D\"}]}"
When executing this code, the data is loaded from my data source, the filter is applied, but the filter bar stays empty.
Is there a way to populate automatically the filter toolbar with values from the filter passed in parameter? I've already tried parsing the filter rules, and filling the inputs with matching values, but I could not find a way to restore the operator.
Since a Guriddo jGrid version 5.3 is used it is good to know that we have rewrite our documentation. Here you can find answer of a lot of your questions. In your case you should know that there is a method which do exactly what you want. The name of the method refreshFilterToolbar. Since in the current implementation of the method the serchOperator are not take into account we have fixed the method in GitHub in order to support them.
If you use the existing method without support for searchOperators your code should like this:
$("#grid").jqGrid({
...
}).filterToolbar({
groupOp: 'AND',
defaultSearch: "cn",
searchOnEnter: true,
searchOperators: true,
stringResult: true
}).refreshFilterToolbar({"filters": result.filter});
and if you use the version from github with support for searchOperators your code should be like this
$("#grid").jqGrid({
...
}).filterToolbar({
groupOp: 'AND',
defaultSearch: "cn",
searchOnEnter: true,
searchOperators: true,
stringResult: true
}).refreshFilterToolbar();
Note that we do not pass the filter parameter, which is get automatically.
I see you use afterInsertRow event to set some class of the row based on condition. This event should be used only if there is no other way to do this. The use of this event in relative big data sets causes a slow reading and in some cases hanging. It should be used very carfully.
In your case you can use rowattr event for this purpose. Please read more about it in the same documentation page. Do not forget to set gridview to true or with other words
...
rowNum: 25,
gridview: true,
rowattr: function (rowdata, rowelem) {
var color = rowelem.Color;
if (color != 'white') {
return { "class" : "color-" + color};
}
},

Select2 Multiple format to be passed to JSON

I am using the select2 multiple for search box. I am passing these data with JSON and saving it using ajax(JSON stringify).
I just need 2 variables passed, which is the ID(primary key, customized) and the Selection itself.
I managed to save it to the database when only 1 value is selected.
When selecting multiple values, in my console.log, I see something like this
{21,23,25,26}
which is the selection itself.
How do I get it show like this,
Object0->{id:1, selection:21}
Object1->{id:2, selection:23}
Object2->{id:3, selection:25}
Object3->{id:4, selection:26}
Below is the code I am using,
var nature = {
ubtBusinessInfo: businessId, // the primary key
ubtBusinessListing: nature.val() // here is selection
};
Here is the initialization of the select2,
nature
.select2({
allowClear: true,
placeholder: "Filter as you type",
minimumInputLength: 3,
multiple: true,
ajax: {
url: 'home/umkei/info/nature',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return { q: term };
},
results: function (data, page) {
return { results: data };
},
cache: true
}
})
nature is defined from(I tried both as below)
var nature = $('[name=nature_business]') OR var nature = $(#nature_business);
I know it must have something to do with the nature.val() usage. Must have been something like array but I dont know how to differentiate/split those data to be key->value pairs.
Thank you.
I got this about last week and thought I'd share my solution.
var nature=[];
var splitnature = nature_business.val().trim().split(',');
var n;
for(n=0; n<=splitnature.length-1;n++){
nature.push({
ubtBusinessListing: splitnature[n],
ubtBusinessInfo: businessId
});
}

jqxListBox:Check listbox item based on value member

Hi I have the following code
var source =
{
datatype: "json",
datafields: [
{ name: 'Name' },
{ name: 'ID'},
],
localdata: data
};
var dataAdapter = new $.jqx.dataAdapter(source);
$("#polistbox").jqxListBox({ source: dataAdapter, displayMember: "Name", valueMember: "ID", checkboxes: true, width: '255px', height: '100px'});
I want to check one item using the value member.
ie) I want to check the item having value 2.How can i achieve this?
I found the following solution http://jsfiddle.net/jqwidgets/vv3gK/ .
But how can i achieve this in my code?
Did you mean check by index or value? Here's an example.
You could always use checkIndex like so:
$("#polistbox").jqxListBox('checkIndex',2);
In the link that you gave me - It showed you everything you need, unless you haven't told us something else.
I know it's old but maybe someone will use it.
This works for me.
var ID = id you want;
var jqItem = $("#polistbox").jqxListBox('getItemByValue', ID);
$("#polistbox").jqxListBox('selectItem', jqItem );

Saving the whole EditorGrid with a single Ajax request

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.

Categories