Populate JqGrid inside ajax call - javascript

I'm trying to populate a JqGrid inside the success function of an Ajax call. My ajax call is passing a date parameter to the function which will filter the results. My grid loads, but no data is displayed and it says Loading... above my grids caption. I'm using a drop down to filter results based on date. My json data has been verified to be valid.
$(document).ready(function () {
$("[name='DDLItems']").change(function () {
var selection = $(this).val();
var dataToSend = {
//holds selected value
idDate: selection
};
$.ajax({
type: "POST",
url: "Invoice/Filter",
data: dataToSend,
success: function (dataJson) {
// alert(JSON.stringify(dataJson));
$("#grid").jqGrid({ //set your grid id
data: dataJson, //insert data from the data object we created above
datatype: json,
mtype: 'GET',
contentType: "application/json; charset=utf-8",
width: 500, //specify width; optional
colNames: ['Invoice_Numbers', 'Amt_Totals','f', 'ff', 't'], //define column names
colModel: [
{ name: 'Invoice_Number', index: 'Invoice_Number', key: true, width: 50 },
{ name: 'Amt_Total', index: 'Amt_Total', width: 50 },
{ name: 'Amt_Due', index: 'Amt_Due', width: 50 },
{ name: 'Amt_Paid', index: 'Amt_Paid', width: 50 },
{ name: 'Due_Date', index: 'Due_Date', width: 50 },
], //define column models
pager: jQuery('#pager'), //set your pager div id
sortname: 'Invoice_Number', //the column according to which data is to be sorted; optional
viewrecords: false, //if true, displays the total number of records, etc. as: "View X to Y out of Z” optional
sortorder: "asc", //sort order; optional
caption: "jqGrid Example", //title of grid
});
},
-- controller
[HttpPost] // Selected DDL value
public JsonResult Filter(int idDate)
{
switch (idDate)
// switch statement goes here
var dataJson = new UserBAL().GetInvoice(date);
return Json(new { agent = dataJson}, JsonRequestBehavior.AllowGet);

Here's the answer if anyone else comes across this. This is what I ended up doing, the rows are getting filtered passed on the date parameter I'm passing to the URL of the function. Having the Grid populate inside the Ajax call also seemed like it was a problem so I had to take it out.
public JsonResult JqGrid(int idDate)
{
switch (idDate)
#region switch date
--Switch Statement--
#endregion
var invoices = new UserBAL().GetInvoice(date);
return Json(invoices, JsonRequestBehavior.AllowGet);
}
[HttpPost] // pretty much does nothing, used as a middle man for ajax call
public JsonResult JqGridz(int idDate)
{
switch (idDate)
#region switch date
--Switch Statement--
#endregion
var invoices = new UserBAL().GetInvoice(date);
return Json(invoices, JsonRequestBehavior.AllowGet);
}
Yes these two functions seem very redundant and they are. I don't know why my post wouldn't update data, but I needed to reload the grid each time and when I did that it would call the first function. So yea the post jqGridz is kinda of just a middle man.
Here's the jquery code I used
var dropdown
var Url = '/Invoice/JqGrid/?idDate=0'
$(document).ready(function () {
$("#jqgrid").jqGrid({
url: Url,
datatype: 'json',
mtype: 'GET', //insert data from the data object we created above
width: 500,
colNames: ['ID','Invoice #', 'Total Amount', 'Amount Due', 'Amount Paid', 'Due Date'], //define column names
colModel: [
{ name: 'InvoiceID', index: 'Invoice_Number', key: true, hidden: true, width: 50, align: 'left' },
{ name: 'Invoice_Number', index: 'Invoice_Number', width: 50, align: 'left'},
{ name: 'Amt_Total', index: 'Amt_Total', width: 50, align: 'left' },
{ name: 'Amt_Due', index: 'Amt_Due', width: 50, align: 'left' },
{ name: 'Amt_Paid', index: 'Amt_Paid', width: 50, align: 'left' },
{ name: 'Due_Date', index: 'Due_Date', formatter: "date", formatoptions: { "srcformat": "Y-m-d", newformat: "m/d/Y" }, width: 50, align: 'left' },
],
pager: jQuery('#pager'),
sortname: 'Invoice_Number',
viewrecords: false,
editable: true,
sortorder: "asc",
caption: "Invoices",
});
$("[name='DDLItems']").change(function () {
var selection = $(this).val();
dropdown = {
//holds selected value
idDate: selection
};
$.ajax({
type: "POST",
url: "Invoice/JqGridz",
data: dropdown,
async: false,
cache: false,
success: function (data) {
$("#jqgrid").setGridParam({ url: Url + selection})
$("#jqgrid").trigger('reloadGrid');
}
})
})
});

Are you actually passing a value to your controller? I see you have data: dataToSend which doesn't match to your controllers idDate.
Is there a reason you are trying to setup your grid this way? Do you not want to deal with paging, or I'm not even sure if your setup would handle rebuild a grid when a user picks the date for a 2nd time.
My personal suggestion would be that you:
setup your grid separately, hidden if you don't want it visible on page load
set it's datatype to local so the grid doesn't load on page load
on the change event:
show the grid
change the postdata parameter the grid has
set the url of the controller/action which will feed the data back to the grid
trigger a grid reload

Related

Why won't data output to jqGrid without the use of "hiddengrid: true"?

I want this:
Without having to start like this:
But for some reason the data only shows up when I use "hiddengrid: true,"
I tried following this demo and was only able to get the example to work by adding "hiddengrid: true," like so:
<body>
<div class="center" id="overGrid">
<table id="jqGrid"></table>
<div id="jqGridPager"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#jqGrid").jqGrid({
url: 'api/codes',
editurl: 'api/codes',
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 75,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
label: 'Id',
name: 'id',
width: 150,
editable: true
},
{
label: 'Title',
name: 'title',
width: 100,
editable: true
},
{
label: 'Code',
name: 'code',
width: 100,
editable: true
},
{
label: 'Original Url',
name: 'originalUrl',
width: 200,
editable: true
}
],
align: 'center',
viewrecords: true,
rowList: [10, 20, 30],
width: 925,
height: 445,
rowNum: 20,
loadonce: true,
hiddengrid: true, // <-------------------- HERE
toppager: '#jqGridPager',
pager: '#jqGridPager',
caption: "Database"
}); jQuery("#jqGrid")
.navGrid('#pager', { edit: false, add: false, del: false, search: false })
.navButtonAdd('#pager', {
caption: "Add",
buttonicon: "ui-icon-add",
onClickButton: function () {
alert("Adding Row");
},
position: "last"
})
.navButtonAdd('#pager', {
caption: "Del",
buttonicon: "ui-icon-del",
onClickButton: function () {
alert("Deleting Row");
},
position: "last"
});
function fetchGridData() {
var gridArrayData = [];
// show loading message
$("#jqGrid")[0].grid.beginReq();
$.ajax({
url: 'api/codes',
mtype: 'POST',
datatype: 'JSON',
success: function (result) {
for (var i = 0; i < result.items.length; i++) {
var item = result.items[i];
gridArrayData.push({
id: item.id,
title: item.title,
code: item.code,
originalUrl: item.originalUrl,
});
}
// set the new data
$("#jqGrid").jqGrid('setGridParam', { data: gridArrayData });
// hide the show message
$("#jqGrid")[0].grid.endReq();
// refresh the grid
$("#jqGrid").trigger('reloadGrid');
}
});
}
fetchGridData();
});
</script>
</body>
Examples such as this don't seem to be working for me on their own so I keep having to reference other sources such as this that are much more complex and informative but possibly the reason for why I continue to have issues every step of the way.
Side Note
I should probably point out that I was only just recently introduced to jqGrid as a result of this question I asked about a week ago: " How can I separate my output using “onclick” and format the data to 20 per page?
"
I did a fairly decent job of documenting the steps that brought me to this point so it might be worth checking out for an in depth look as to what I am dealing with.
In short I am building an API in Asp.Net Core that sends and receives JSON data to my MongoDb database and then outputs the data to a single HTML page using jqGrid. So far I have created functioning Get, Post, Put, and Delete methods that return and send JSON data to my MongoDb database.
Update:
I have gone through the docs suggested by Tony Tomov and I understand their meaning. I just haven't the slightest clue to the solution to this problem. Everything I have thought to be a possible solution and tried from before and after I posted this question has given me a blank page without any errors.

Free jqGrid, don't send new index on addrow with inlineNav

Just putting in a new grid, and everything seems to be working well, except for one thing. Using basic inline, it is sending a new incorrect key value for the column I have set with key: true. This is an auto-increment column in the database, so I just don't want to send any data for this column when ADDING, only for edit or delete is that required.
It is posting a parameter: row_id => jqg3 for the new key column and messing up my server script. So because adding the new row will auto-increment the row_id col, I don't need to send this.
How do I stop the jqGrid from sending this (row_id) index column value when saving a new added row?
free-jqgrid version is 4.14.0
$('#accts').jqGrid({
url:'/phpAJAX/Master/master_grid_v1.php',
editurl:'/phpAJAX/Master/master_grid_v1.php',
height: 'auto',
shrinkToFit: false,
width: 'auto',
datatype: 'xml',
mtype: 'POST',
postData:{
'arg1':'bol_acct'
},
colNames:[
'row_id',
'Customer',
'Trucker',
'Acct Num'
],
colModel:[
{name: 'row_id', hidden: true, key: true},
{name:'Customer', align: "center", editable: true},
{name: 'Trucker', align: "center"},
{name: 'Acct_Num', align: "center"}
],
sortname: 'Customer',
sortorder: 'desc',
viewrecords: true,
gridview: true,
caption: 'Bill of Lading Accounts',
rowNum: 10000,
pager:true
}).jqGrid('inlineNav', {
addParams: {
addRowParams: { extraparam: {'arg1':'bol_acct', 'oper':'add'} }
},
editParams: {
extraparam: {
'arg1':'bol_acct', 'oper':'edit'
}
}
})
One can use serializeSaveData callback of inline editing to modify the data, which will be send during inline editing. You can add serializeSaveData callback via
inlineEditing: {
keys: true,
extraparam: { arg1: "bol_acct" },
serializeSaveData: function (postData) {
var newPostData = $.extend(true, {}, postData);
if (newPostData.oper === "add") {
delete newPostData.id; // delete id parameter
}
return newPostData;
}
}

Jqgrid having trouble loading all data from the server using loadonce

so I have a grid that uses loadonce set to true and rowTotal to spicify the number of rows returned. My database has about 200,000 records, however it seems to timeout if I set the return to that amount, I can only really load about 20,000 records without any problems. Is there a way to make it return everything from the database? My query I use to retrieve the values is
public IEnumerable<vwWell> GetAll()
{
return from e in db.vwWells
select e;
}
my web API code is
static readonly IWellRepository repository = new WellRepository();
WellsMigrationEntities db = new WellsMigrationEntities();
// GET api/values
public dynamic Get(string sidx, string sord, int page, int totalrows)
{
var wells = repository.GetAll() as IEnumerable<vwWell>;
var pageIndex = Convert.ToInt32(page) - 1;
var pageSize = totalrows;
var totalRecords = wells.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
wells = wells.Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalrows,
page = page,
records = totalRecords,
rows = wells.ToArray() //We need an array of objects for the rows
};
return jsonData;
}
and my grid code is
<script>
var API_URL = "http://localhost:41389/api/well";
jQuery("#gridMain").jqGrid({
url: API_URL,
datatype: "json",
mtype: 'GET',
loadonce: true,
gridview: true,
autowidth: true,
sortable: true,
viewrecords: true,
colNames: ['Id', 'APINumber', 'CountyName', 'LeaseName'],
colModel: [
{ name: 'WellKey', index: 'WellKey', width: 55, sorttype: "int", hidden: true},
{ name: 'APINumber', index: 'APINumber', width: 90, sorttype: "text" },
{ name: 'CountyName', index: 'CountyName', width: 100, sorttype: "text" },
{ name: 'LeaseName', index: 'LeaseName', width: 80, sorttype: "text" }
],
pager: '#pager3',
rowNum: 200,
rowTotal: 20000,
jsonReader: { repeatitems: false, id: "WellKey" },
rowList: [200, 300, 500],
sortname: 'WellKey',
sortorder: "desc",
caption: "JSON Example"
});
See how I have rowTotal set to 20,000, if I dont set that nothing returns, but it seems I am limited in the number of rows it is able to return.

jqGrid pagination not working with json datatype

I can't seem to get jqGrid pagination to work. It is not making a request when I click next/prev/reload or when I try to filter. As soon as I click any of those buttons, all of the records disappear.
This is the initial request that gets sent, so you can see that all of those parameters are being passed in.
https://www.xxxxxxx.com/getallorders?contactId=333&bucketId=444&_search=false&nd=1366982305621&rows=2‌​0&page=1&sidx=PKId&sord=desc
This returns proper number of records, and if I manually execute it and pass in let's say page=2 I do get proper set back. The problem seems to be that the request is not made.
jQuery("#grid").jqGrid({
url:'/GetAllOrders',
mtype: "GET",
datatype: "json",
jsonReader: {
root: "Rows",
page: "Page",
total: "Total",
records: "Records",
repeatitems: false,
userdata: "UserData",
id: "Id"
},
postData: {
contactId: currentUserId,
bucketId: currentBucketId
},
colNames:[
'Id',
'Cancel',
'Order #',
'Order Date',
'Bucket',
'Warehouse',
'Destination',
'Status',
'Tracking #',
'Transport By',
'Ordered By',
'Order Items'
],
colModel:[
{name:'Id',index:'Id', width:5, align:"center", hidden: true},
{name:'Cancel', index:'Cancel',width:80, align:"center", formatter: cancelLinkFormatter, search:false },
{name:'OrderNumber',index:'OrderNumber', width:80, align:"center"},
{name:'OrderDate',index:'OrderDate', width:140, align:'right'},
{name:'Bucket',index:'Bucket', width:180, align:"center", hidden: false},
{name:'Warehouse',index:'Warehouse', width:80, align:"center", hidden: true},
{name:'Destination',index:'Destination', width:150},
{name:'StatusCode', index:'StatusCode', width:100, align: 'center'},
{name:'TrackingNumber', index:'TrackingNumber', width:100, align: 'center'},
{name:'TransportCompany', index:'TransportCompany', width:100, align: 'center'},
{name:'OrderedBy', index:'OrderedBy', width:100, align: 'center'},
{name:'OrderItems', index:'OrderItems', width:100, align: 'center'}
],
viewrecords: true,
rowNum: 20,
autowidth: false,
width: 860,
height: 450,
rowList:[10,20,30,40,50],
pager: jQuery('#pager'),
sortname: 'Id',
align: 'center',
sortorder: "desc",
loadonce: false,
ignoreCase: true,
caption:"Orders"
}).navGrid('#pager',{edit:false,add:false,del:false});
setSearchSelect('StatusCode');
jQuery("#grid").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch: "cn"});
This is the json response I get from the server on initial load.
{
"Total":2,
"Page":1,
"Records":28,
"Rows":[
{
"PKId":1234,
"OrderNumber":"XXXXXX97",
"Cancel":"Cancel",
"OrderDate":"Jul 11 2012 12:37PM",
"Warehouse":"",
"Bucket":"xxxxxxxx",
"StatusCode":"Shipped Complete",
"StatusLink":"View Info",
"TrackingNumber":"xxxxxxx",
"TransportCompany":"xxxxxxxx",
"Destination":"xxxxxxx",
"BucketId":110,
"ShippingEmail":"xxxxxxxx",
"OrderedBy":"xxxxxxxx",
"OrderItem":"xxxxxxx"
},
.... MORE DATA HERE ... 20 OBJECTS ALL-TOGETHER WITHIN Rows Array
{
"PKId":13434,
"OrderNumber":"XXXXXX97",
"Cancel":"Cancel",
"OrderDate":"Jul 11 2012 12:37PM",
"Warehouse":"",
"Bucket":"xxxxxxxx",
"StatusCode":"Shipped Complete",
"StatusLink":"View Info",
"TrackingNumber":"xxxxxxx",
"TransportCompany":"xxxxxxxx",
"Destination":"xxxxxxx",
"BucketId":110,
"ShippingEmail":"xxxxxxxx",
"OrderedBy":"xxxxxxxx",
"OrderItem":"xxxxxxx"
},
],
"UserData":null
}
Any suggestions?
Btw, the pagination and filtering was working just fine when I used loadonce: true and when I loaded all data at once, however, due to too many records I simply have to switch to server-side.
EDIT
I found the problem. First of all, I am sorry for not including the rest of the code.
You see, I also had loadComplete and that was causing the problem for me.
Code in the question will work, so I want to thank everyone for participating.
This is the loadComplete that caused the problem. Once I removed it it started paging properly.
loadComplete: function() {
setParamsOnComplete();
var myGrid = jQuery("#grid");
var ids = myGrid.getDataIDs();
for (var i = 0, idCount = ids.length; i < idCount; i++) {
jQuery("#"+ids[i]+" a",myGrid[0]).click(function(e) {
var hash=e.currentTarget.hash;// string like "#?id=0"
if (hash.substring(0,6) === "#S?id=") {
var id = hash.substring(6,hash.length);
var text = this.textContent || this.innerText;
dialog.dialog({ title: 'Status Information',
buttons:{ Ok: function() {
jQuery( this ).dialog("close");
}
},
open: function() {
jQuery('.ui-dialog-buttonpane').find('button:contains("Ok")').css('font-size', '10px');
}
});
dialog.dialog('open');
}
if (hash.substring(0,6) === "#C?id=") {
var id = hash.substring(6,hash.length);
var text = this.textContent || this.innerText;
var changed = false;
var additionalMesages = "";
jQuery.post("DataFetcher.asp", { 'action': "cancelOrder", 'id':id }, function(xml) {
changed = (xml === 'True');
additionalMesages = xml;
}).success(function(){
if (changed){
showDialogCustomTitle("Success", "You've successfully cancelled the order " + id + ".");
jQuery("#grid").setGridParam({datatype:'xml', page:1}).trigger('reloadGrid');
}else if (additionalMesages.split("_")[1] == "2"){
showDialogCustomTitle("Error", additionalMesages.split("_")[2]);
}else if (additionalMesages.split("_")[1] == "1"){
showDialogCustomTitle("Error", additionalMesages.split("_")[2]);
}
});
}
//e.preventDefault();
});
}
},
Next task for me is to perhaps figure out why loadComplete cause the problem.
EDIT 2
Found the first issue with loadComplete. I was too tired last night to notice it, but the leftover code from the period when this grid was populated with xml and paged on client side definitely caused the problems. Thank you all for involvement again. :)
jQuery("#grid").setGridParam({datatype:'xml', page:1}).trigger('reloadGrid');
Since you have set loadonce:false, the request for paging and filtering try to get processed at the server side. Since that may not probably happening in your case, there will be no data to return to and set in the jqGrid.
If you are using loadonce:false and datatype:"json" jqGrid option then your server must implement the pagination of your grid. The server receives some parameters which is appended to the url in case of the 'GET' requests or sent in the HTTP body in case of "POST" requests namely : rows, page, sidx, sord.
For example if your table have a column with the index 'Col1' as the current sort column and rowNum: 20 then your url will be appended with baseUrl?rows=20&page=1&sidx=Col1&sord=asc. Your server side coding should modify your query for data so that it is to be having ORDER BY (Col1 datafield in the table) asc and rowNum from 1 to 20.
If you have done as stated above and it is not working, you should verify your server code.

How can I get checked row ids? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm using jqGrid, and I add a checkbox column, I want to be able to get checked rows so I can call the server with them...
My jqGrid Code:
<script type="text/javascript">
$(function () {
$("#UsersGrid").jqGrid({
url: "Handler.ashx",
datatype: 'json',
height: '100%',
width: '500',
colNames: [' ', 'ref#', 'Module', 'TT#', 'AssignedOn', 'TrialNo'],
colModel: [
{ name: ' ', index: 'ChkBox', width: 16, sortable: false, editable: true, formatter: "checkbox", formatoptions: { disabled: false }, editable: true, edittype: "checkbox" },
{ name: 'ref#', width: 50, sortable: true },
{ name: 'Module', width: 50, sortable: true },
{ name: 'TT#', width: 110, sortable: true },
{ name: 'AssignedOn', width: 110, sortable: true },
{ name: 'TrialNo', width: 50, sortable: true }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: '#UsersGridPager',
sortname: ' ',
viewrecords: true,
sortorder: 'asc'
//caption: "Cases"
});
$("#UsersGrid").jqGrid('navGrid', '#UsersGridPager', { edit: false, add: false, del: false });
</script>
Thanks in Advance...
You should better you multiselect:true, because the functionality i can see you are implementing with check boxes is to select multiple rows.
here's how it will work for u.
1. Make multiselect:true in jqgrid Parameters.
add one button to your html like this
button type="button" value="submit" id="clickMe" >Submit /button> //start and close the tags properly.
Now on the click event of this button, get the data of selected rows and make one ajax request to your server.
$('#clickMe').click(function(){
var selRowIds = $('#grid').jqGrid('getGridParam', 'selarrrow');
if(selRowIds.length>0)
{
for( var i=0;i<selRowIds.length;i++){
var ref#=getCellValue(selRowIds[i],'ref#');
var Module=getCellValue(selRowIds[i],'Module');
var TT#=getCellValue(selRowIds[i],'TT#');
var AssignedOn=getCellValue(selRowIds[i],'AssignedOn');
var TrialNo=getCellValue(selRowIds[i],'TrialNo');
$.ajax({
type: 'POST',
url: '#Url.Action("editMe")',
contentType: 'application/json; charset=utf-8',
data:JSON.stringify({ref#: ref#, Module:Module,TT#:TT#,AssignedOn:AssignedOn,TrialNo:TrialNo}),
dataType: "json",
success:function(){
$('#grid').trigger("reloadGrid");
},
error: function () {
alert("error");
}
});
}
}
});
and your controller should look like this
public ActionResult editMe(string ref#, string Module, string TT#, string AssignedOn, string TrialNo)
{
}
I'm assuming you have dataType for all the columns as string and they all are editable:true(you can mention this with colModal. So if only Module, AppliedOn is editable true, so you can get only these two values in button click. depending upon your need you can change the code.
You don't have to add the checkbox column manually. Here's how I do it:
Specify the editurl and multiselect options:
$("#UsersGrid").jqGrid({
// The grid will send modification data to this url
//
editurl: "url which will handle the edit/delete operations",
// This ensures there will be a checkbox column in your grid
//
multiselect: true,
...
});
Provide a handler for the modification operations (responding to the editurl requests). In my case, it is an action method with this signature:
public ActionResult EditItems(string id, string oper, string source, string target)
{
// id: list of IDs of the selected items (e.g. "1234,5678")
// oper: the requested operation ("edit" or "del", if you use the standard ones)
// source, target: in case of the "edit" operation, these are the new values of the respective columns. I.e. these parameters are model-specific (I have "source" and "target" columns in my grid)
}

Categories