jqgrid modify post data in upload image row - javascript

I just make functional on my application in order to upload image, convert it to base64 and send to server as base64 string.
I found function to convert image to base64. It works fine. I use jqgrid standart forms to create and edit data. Image uploads but I need to change post data before post to add base64 string to param value.
I use serializeEditData but it works faster than my function converts image to string. I used callback function and it doesn't work.
serializeEditData: function (postData) {
var fileContainer = document.getElementById('photo').files;
var reader = new FileReader();
reader.readAsDataURL(fileContainer[0]);
reader.onload = function () {
postData.image = reader.result;
};
/* I used this too
var fileContainer = document.getElementById('photo').files;
getBase64(fileContainer[0], function (result) {
postData.image = result;
});*/
return postData;
},
If I console log formData before return statement it shows me postData with image base64 string. But problem what return statement works faster than postData.image set string.
My getBase64 function code:
function getBase64(file, callback) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
callback(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
And my full code:
jQuery(function ($) {
var quiz_table_id = $("#quiz_table_id");
var quiz_pager_id = "#quiz_pager_id";
var colNames = ['id', 'title', 'description', 'section', 'section', 'image', 'image'];
var postDataGlobal;
var template = {width: 160, fixed: true, align: 'center', editable: true, stype: 'text'};
var colModel = [
{
name: 'id',
index: 'id',
sortname: 'id',
editable: true,
sorttype: 'number'
},
{
name: 'title',
index: 'title',
sortname: 'title',
template: template,
sorttype: 'number'
},
{
name: 'description',
index: 'description',
sortname: 'description',
width: 120,
fixed: true, align: 'center', editable: true,
template: "number",
sorttype: 'number'
},
{
name: 'section.name',
sortname: 'section.name',
formatter: null,
sorttype: 'number',
editable: false
},
{
name: 'section.id',
sortname: 'section.id',
formatter: 'select',
edittype: "select",
hidden: true,
editable: true,
editrules: {edithidden: true, required: true},
editoptions: {value: "1:Java"}
/*editoptions: {
dataInit: function (elem) {
$.get("http://localhost:8080/section/get-all-map", function (data, status) {
$(elem).empty();
Object.keys(data).map(function (key, index) {
console.log(data[key] + " " + key);
$(elem).append("<option value=" + key + ">" + data[key] + "</option>")
});
});
}
}*/
},
{
name: 'image',
index: 'image',
sortname: 'image',
template: template,
sorttype: 'number',
editable: true
},
{
name: 'photo',
index: 'photo',
search: false,
editable: true,
edittype: 'file',
editoptions: {
enctype: "multipart/form-data"
},
align: 'center',
}
];
quiz_table_id.jqGrid({
url: 'http://localhost:8080/quiz/get-all',
datatype: "json",
jsonReader: {
repeatitems: true
},
height: 'auto',
colNames: colNames,
colModel: colModel,
shrinkToFit: false,
forceFit: true,
pager: quiz_pager_id,
toppager: true,
rowNum: 10,
rowList: [5, 10, 15, 20, 25, 30],
loadonce: true,
colMenu: true,
menubar: true,
viewrecords: true,
storeNavOptions: true,
editurl: 'http://localhost:8080/quiz/save',
loadComplete: function () {
},
gridComplete: function () {
}
});
//navButtons
quiz_table_id.jqGrid('navGrid', quiz_pager_id,
// the buttons to appear on the toolbar of the grid
{
edit: true,
add: true,
del: true,
search: true,
refresh: true,
view: true,
position: "left",
cloneToTop: false
},
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
recreateForm: true,
checkOnUpdate: true,
checkOnSubmit: true,
closeAfterEdit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
},
serializeEditData: function (postData) {
var fileContainer = document.getElementById('photo').files;
var reader = new FileReader();
reader.readAsDataURL(fileContainer[0]);
reader.onload = function () {
postData.image = reader.result;
};
/* I used this too
var fileContainer = document.getElementById('photo').files;
getBase64(fileContainer[0], function (result) {
postDataGlobal.image = result;
});*/
return postData;
},
beforeSubmit: function (data) {
return [true, ''];
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dailog
{
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
{
multipleSearch: true,
showQuery: true
} // search options - define multiple search
);
$(window).triggerHandler('resize.jqGrid');
quiz_table_id.triggerHandler("jqGridAfterGridComplete");
});
function getBase64(file, callback) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
callback(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}

Related

Cannot read property 'length' of null in script

I'm trying to call a function from code behind in script. That function i just returning list of employee
i'm just trying not to use grid view.
I just copy the code in at the same project and changes the names of function and the name inside the colModel: []
here's my script:
function loadMoretha60grid() {
$('#timesheetgrid').jqGrid("GridUnload");
getmoreThan60(function (data) { loadTimesheetTableMoeretha60(data); });
}
function loadTimesheetTableMoeretha60(timelog) {
var lastsel;
var startpage = 1;
$('#timesheetgrid').jqGrid({
datatype: 'local',
data: timelog,
editurl: 'clientArray',
colNames: ['CompanyID', 'EMPName', 'START_DATE', 'END_DATE',
'TOTALHOURS'],
colModel: [
{ name: 'CompanyID', index: 'CompanyID', editable: 'false', align: 'center', width: '150', sortable: false, },
{ name: 'EMPName', index: 'EMPName', editable: 'false', align: 'center', width: '275', resizable: false },
{ name: 'START_DATE', index: 'START_DATE', editable: 'false', align: 'center', width: '175', resizable: false },
{ name: 'END_DATE', index: 'END_DATE', editable: 'false', align: 'center', width: '175', resizable: false },
{ name: 'TOTALHOURS', index: 'TOTALHOURS', editable: 'false', align: 'center', width: '175', resizable: false },
],
pager: '#timesheetgridpager',
viewrecords: true,
forceFit: false,
shrinkToFit: false,
width: '1000',
emptyrecords: "No Record/s found",
loadtext: "Loading",
rowList: [5, 10, 20, 50],
height: 'auto',
caption: 'Timesheet Listing'
});
$('#timesheetgrid').jqGrid('navGrid', '#timesheetgridpager', {
edit: false,
save: false,
add: false,
cancel: false,
del: false,
search: false,
refresh: false
});
$('#timesheetgrid').jqGrid('inlineNav', '#timesheetgridpager', {
add: false,
edit: false,
save: false,
cancel: false,
restoreAfterSelect: false
});
}
function getmoreThan60(callback) {
var timelog = [],
params = {
name: $('#empnamebox').val(),
dateStart: '2019-09-01',
dateEnd: '2019-09-29'
};
showLoadingGif();
$.ajax({
async: true,
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Timesheet.aspx/getMore60hrs',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
timelog = data.d;
hideLoadingGif();
if (typeof callback != 'undefined')
callback(timelog);
},
error: function (xhr, status, error) {
console.log(xhr, status, error);
hideLoadingGif();
}
});
}
here's my method
[WebMethod]
public static void getMore60hrs(string name,string dateStart,string dateEnd) {
TDKDataAccessLayer dataAcc = new TDKDataAccessLayer();
List<morethan> records = new List<morethan>();
dataAcc.DepartID = Convert.ToInt32(DeptID);
dataAcc.Name = name;
dataAcc.DateStart = dateStart;
dataAcc.DateEnd = dateEnd;
records = dataAcc.MoreThan60hrs();
}
By the way
I don't know what to do about this because i came from windows form c#

jqGrid inline-edit POST without editurl?

I am trying to find the information about editurl. Currently, i am working on the framework which does not permit editurl. The calls must go through javascript function which in-turn invokes the component on serverside.
Question is it possible to POST the data to javascript function instead of editurl?
I am experimenting with following:
$(document).ready(function () {
console.log(">>>1");
//--
action.setCallback(this, function(a) {
if (a.getState() === "SUCCESS") {
result = a.getReturnValue();
console.log(result);
//---=
var editActionOptions = {
keys: true,
url:null,
oneditfunc: function (rowid) {
console.log("row with rowid=" + rowid + " is editing.");
},
aftersavefunc: function (rowid, response, options) {
console.log("row with rowid=" + rowid + " is successfuly modified.");
}
};
//-------------------------------------------------------------------------------------------------------
$("#jqGrid").jqGrid({
editurl: 'clientArray',
datatype: "local",
data:result,
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
labe: 'ID',
name: 'empid',
width: 75
},
{
label : 'Name',
name: 'Name',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label: 'dob',
name: 'dob',
width: 100,
editable: true
},
{
label: 'dln',
name: 'dln',
width: 120,
editable: true
}
],
sortname: 'empid',
loadonce: true,
onSelectRow: editRow,
onSave:onSaveRow,
editParams: editActionOptions,
width: 780,
height: 400,
rowNum: 150,
pager: "#jqGridPager"
});
//------------------------------------------------------------------------------------------------------
} else if (a.getState() === "ERROR") {
$A.log("Errors", a.getError());
}
});
$A.enqueueAction(action);
var lastSelection;
function editRow(id) {
console.log(id);
if (id && id !== lastSelection) {
var grid = $("#jqGrid");
grid.jqGrid('restoreRow',lastSelection);
grid.jqGrid('editRow',id, {keys: true} );
lastSelection = id;
}
};
function onSaveRow(id){
console.log(id);
}

Unable to bind the data to dropdown in jqgrid when it is editing getting data using web api

$j(document).ready(function () {
$j.ajax({
type: "GET",
url: "http://localhost:9611/api/Master/GetBackendUsersList",
contentType: "json",
dataType: "json",
success: function (data) {
var dataList;
var StatusList = '';
$j('#list2').jqGrid({
caption: "Users Details",
data: data,
datatype: "local",
height: '100%',
width: '100%',
colNames: ["UserName", "RoleId", "Name", "RoleName", "LoginId"],
colModel: [
{ name: "UserName", index: 'UserName', editable: true },
{ name: 'RoleId', index: "RoleId", hidden: true, width: 150, editable: true },
{ name: "Name", index: "Name", editable: true },
{
name: "RoleName", index: "RoleName", editable: true, edittype: 'select', editoptions: {
dataInit: function (element)
{
$j.ajax({
type: "GET",
url: "http://localhost:9611/api/Master/GetRoles",
contentType: "json",
dataType: "json",
success: function (mydata) {
dataList = mydata;
for (var i = 0; i < dataList.length; i++) {
//if (StatusList == "")
// StatusList = dataList[i].RoleId + ":" + dataList[i].RoleName;
//else
StatusList = StatusList + dataList[i].RoleId + ":" + dataList[i].RoleName+ ';' ;
}
}
});
},
value: "0:Select;" + StatusList,
}
},
{ name: 'LoginId', index: "LoginId", hidden: true, width: 150 }
],
gridview: true,
rowNum: 5,
rowList: [5, 10, 15],
pager: '#jQGridDemoPager',
sortname: "UserName",
viewrecords: true,
sortorder: "desc",
//width: '100%',
//height: '100%',
shrinkToFit: false,
editurl: SiteUrl + "api/Master/UpdateBackendUserDetails/" ,
});
$j.extend(true, $j.jgrid.edit, {
recreateForm: true,
beforeShowForm: function ($jform) {
$jform.closest(".ui-jqdialog").position({
of: window, // or any other element
my: "center center",
at: "center center"
});
}
});
$j('#list2').jqGrid('navGrid', '#jQGridDemoPager',
{
add: false,
search: false,
recreateForm: true,
beforeShowForm: function ($jform) {
$jform.find(".FormElement[readonly]")
.prop("disabled", true)
.addClass("ui-state-disabled")
.closest("LoginId")
.prev(".CaptionTD")
.prop("disabled", true)
.addClass("ui-state-disabled");
},
},
{ recreateForm: true }
);
}
});
});
Dropdown data from api is like:
[{"RoleId":1,"RoleName":"Administrator"},{"RoleId":2,"RoleName":"Sales"},{"RoleId":3,"RoleName":"Secretory/President"},{"RoleId":4,"RoleName":"Apartment Owner"},{"RoleId":5,"RoleName":"Apartment User"}]
Use this way :
editoptions:{value: getData()}
and then create one method
function getData(){
var states = [{"RoleId":1,"RoleName":"Administrator"},{"RoleId":2,"RoleName":"Sales"},{"RoleId":3,"RoleName":"Secretory/President"},{"RoleId":4,"RoleName":"Apartment Owner"},{"RoleId":5,"RoleName":"Apartment User"}];
return states;
}
In your case you need to add ajax call in getData() and return values/array which has been created by the result.

JQGrid date sorting and search

I am currently displaying a particular set of data in jqgrid. I want to sort and search the column Job Date, but it does not work.
The date is being displayed as 2015-08-26 but neither sorting nor search works.
Am I missing something.
var gridSelector = "#tblist";
var emptyMsgDiv = $("<div style=\"text-align:center\"><span style='color:red;font-size:24px'>No records found</span></div>");
jQuery(gridSelector).jqGrid({
url: '#Url.Action("ListActivities", "DailyActivity")',
loadonce: true,
datatype: 'json',
shrinkToFit: true,
autowidth: true,
mtype: 'GET',
ignoreCase: true,
colNames: ['Edit', 'ActivityID', 'Job No', 'Job Date',...],
colModel: [
{ name: 'Edit', index: 'Edit', formatter: EditBind, width: '50px', search: false, sortable: false },
{ name: 'ActivityID', index: 'ActivityID', hidden: true },
{ name: 'DOWJobNumber', index: 'DOWJobNumber', align: 'left', width: '100px' },
{
name: 'DOWJobDate', index: 'DOWJobDate', width: '70px',
formatter: 'date',
sorttype: 'date',
formatoptions: {srcformat:'ISO8601Long', newformat: 'ISO8601Short' },
datefmt: 'ISO8601Short',
searchoptions: {
sopt: ['eq', 'gt', 'ge'],
dataInit: function (el) {
$(el)
.datepicker({ dateFormat: "yy-mm-dd" })
.change(function () {
$(gridSelector)[0].triggerToolbar();
});
}
}
},
{ ... },...
],
height: 'auto',
pager: '#gridpager',
rowNum: 20,
rowList: [5, 10, 20, 50, 100],
sortname: 'ActivityID',
sortorder: 'desc',
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
},
loadError: function (xhr, st, err) {
bootbox.alert("Error retrieving data!");
},
emptyrecords: 'No Records found',
loadComplete: function () {
emptyMsgDiv.insertAfter($('#tblist').parent());
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
}
})
.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
Edit: It looks like the search is being made on the JSON format(/Date(1430937000000)/). How can this be changed to search and sort using the specified date format
I had to format the date time as text in the controller and processed it in the JQGrid as below
{
name: 'DOWJobDateText', index: 'DOWJobDateText', width: '80px',
formatter: 'date',
sorttype: 'date',
formatoptions: { srcformat: 'd/m/Y', newformat: 'd/m/Y' },
datefmt: 'd/m/Y',
searchoptions: {
dataInit: function (el) {
$(el)
.datepicker({ dateFormat: "dd/mm/yy" })
.change(function () {
$(gridSelector)[0].triggerToolbar();
});
}
}
}

Unable to set date format & dropdown text in jqGrid

I am using jqGrid to display data. Data is in xml format.
I am unable to format date column (source format : yyyyMMdd, target format : dd-mm-yyy).
My Grid is unable to display text value from select, It shows values instead of text.
Strange thing is it is working in some other screen.
<SalesOpportunitiesLines>
<row>
<LineNum>0</LineNum>
<SalesPerson>1</SalesPerson>
<StartDate>20131126</StartDate>
<ClosingDate>20131126</ClosingDate>
<StageKey>1</StageKey>
<PercentageRate>0.000000</PercentageRate>
<MaxLocalTotal>1000000.000000</MaxLocalTotal>
<DocumentType>bodt_MinusOne</DocumentType>
<BPChanelName>ACCM Services</BPChanelName>
<BPChanelCode>CLINAC0709</BPChanelCode>
<SequenceNo>366</SequenceNo>
<DataOwnershipfield>1</DataOwnershipfield>
<BPChannelContact>1212</BPChannelContact>
</row>
</SalesOpportunities>
$("#uxStages").jqGrid({
datatype: 'xmlstring',
datastr: xmlstring,
mtype: 'GET',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
xmlReader: { repeatitems: false, root: "BO>SalesOpportunitiesLines", row: 'row' },
colNames: ['LineNum', 'Star tDate', 'Clos Date', 'Sales Employee', 'Stage', 'Percentage', 'Potential Amount', 'Document Type', 'Doc. No.', 'Owner'],
colModel: [
{ name: 'LineNum', key: true, index: 'LineNum', hidden: true, sortable: false, width: 60 },
{ name: 'StartDate', key: false, index: 'StartDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'yyyyMMdd', newformat: 'd-M-y' },
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'ClosingDate', key: false, index: 'ClosingDate', sortable: false, align: "left", width: 90,
editable: true,
formatter: 'date',
formatoptions: { srcformat: 'yyyyMMdd', newformat: 'd-M-y' },
editoptions: {
dataInit: function (elem) {
$(elem).datepicker({ dateFormat: 'dd-M-yy' });
}
}
},
{ name: 'SalesPerson', key: false, index: 'SalesPerson', sortable: false, width: 80,
editable: true,
edittype: "select"
},
{ name: 'StageKey', key: false, index: 'StageKey', hidden: false, sortable: false, width:80,
editable: true,
edittype: "select"
},
{ name: 'PercentageRate', key: false, index: 'PercentageRate', sortable: false, width: 60 },
{ name: 'MaxLocalTotal', key: false, index: 'MaxLocalTotal', sortable: false, width: 100,
editable: true,
edittype: "text",
formatter: 'currency',
formatoptions: { thousandsSeparator: ',' }
},
{ name: 'DocumentType', key: false, index: 'DocumentType', sortable: false, width: 90,
editable: true,
edittype: 'select',
formatter: 'select',
editoptions: { value: "bodt_MinusOne:;bodt_Quotation:Sales Quotations;bodt_Order:Sales Orders;bodt_DeliveryNote:Deliveries;bodt_Invoice:A/R Invoice" }
},
{ name: 'DocumentNumber', key: false, index: 'DocumentNumber', sortable: false, width: 40 },
{ name: 'DataOwnershipfield', key: false, index: 'DataOwnershipfield', hidden: false, sortable: false, width: 60,
editable: true,
edittype: "select"
}
],
rowNum: 100,
viewrecords: true,
gridview: true,
rownumbers: true,
height: 150,
loadonce: true,
width: 1120,
scrollOffset: 0,
ondblClickRow: function (rowid) {
var grid = $("#uxStages");
var selectedRowId = grid.jqGrid('getGridParam', 'selrow');
lastSelection = selectedRowId;
grid.jqGrid('editRow', selectedRowId, true, null, null, null, null, OnSuccessEdit_Stages);
$('#' + selectedRowId + "_StageKey").css('width', '100%');
$('#' + selectedRowId + "_SalesPerson").css('width', '100%');
$('#' + selectedRowId + "_DataOwnershipfield").css('width', '100%');
},
loadComplete: function () {
var ids = $("#uxStages").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
if (i < ids.length - 1) {
$('#' + $.jgrid.jqID(id)).addClass('not-editable-row');
$('#' + $.jgrid.jqID(id)).addClass('ui-state-error');
}
}
},
onSelectRow: function (id) {
if (id && id !== lastSelection) {
var grid = $("#uxStages");
$('#uxStages').saveRow(lastSelection);
}
}
}).jqGrid('navGrid', { edit: true, edit: true, add: true, del: true, searchOnEnter: false, search: false }, {}, {}, {}, { multipleSearch: false }).trigger('reloadGrid');
$("#uxStages").setColProp('SalesPerson', { edittype: "select", editoptions: { value: GetSalesValues()} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('StageKey', { edittype: "select", editoptions: { value: GetStagesValues()} }); //Here i m fetching values in namedvalue pairs
$("#uxStages").setColProp('DataOwnershipfield', { edittype: "select", editoptions: { value: GetDataOwnershipValues()} }); //Here i m fetching values in namedvalue pairs
Can anybody help me out?
The predefined formatter: "date" of jqGrid don't support input fields without separators. So you have to use custom formatter. The implementation could be something like the following
formatter: function (cellValue, opts, rawdata, action) {
if (action === "edit") {
// input data have format "dd-mm-yy" format - "20-03-2015"
var input = cellValue.split("-");
if (input.length === 3) {
return input[0] + "-" + input[1] + "-" + input[2];
}
} else if (cellValue.length === 8) {
// input data have format "yymmdd" format - "20150320"
var year = cellValue.substr(0,4), month = cellValue.substr(4,2),
day = cellValue.substr(6,2);
return day + "-" + month + "-" + year;
}
return cellValue; // for empty input for example
}
Depend on other options (like the usage of loadonce: true) and depend on exact version of jqGrid which you use, you could need to implement additional callbacks in the column. For example if you use loadonce: true then the editing data will be saved locally. To hold the data in the same format as input data one can use saveLocally callback of free jqGrid (see here). In the case you can implement saveLocally callback in the column as the following
saveLocally: function (options) {
var input = String(options.newValue).split("-");
options.newItem[options.cmName] = input.length === 3 ?
input[2] + input[1] + input[0] :
options.newValue;
}
See the corresponding demo uses the above code. It uses local input data in the same format. The date will be displayed in the desired format, but the edited data will be saved locally in the same format like original date.

Categories

Resources