How to show jqgrid data dynamically using entityframwork with sql data? - javascript

hi bosses i have used sql pivot to show employeewise product in grids. when i execute the query in management studio it is working fine but the problem is when i want to show data in jqgrid in with dynamic rows and columns it is not working. I am new in jqgrid.
here is my controller action method
public ActionResult FindOrderByEmployeeCall()
{
var query = (from fo in db1.FindOrderByEmp1()
select fo).ToList();
return Json(query, JsonRequestBehavior.AllowGet);
}
my ajax method for show data in jqgrid in view page is
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Invoice/FindOrderByEmployeeCall/",
dataType: "json",
success: function(result){
var colD = result.couponStripList,
colM = result.colModelList;
$("#list").jqGrid({
//datatype: 'local',
data: "",
gridview: true,
colModel :colM,
height: "auto",
loadComplete: function(data){
alert('loaded');
},
loadError: function(xhr,status,error){
alert('error');
}
});
},
error: function(x, e){
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
});
</script>
and my sql pivot query is
ALTER proc [dbo].[FindOrderByEmp1]
as
BEGIN
SET FMTONLY OFF;
DECLARE #query nvarchar(max)
DECLARE #Product NVARCHAR(max),#Product1 NVARCHAR(max)
SELECT #Product = STUFF(( SELECT distinct'],['+ rtrim(ProdId) FROM OrderDetails ORDER BY '],['+ rtrim(ProdId) FOR XML PATH('')), 1, 2, '')+']'
set #Product1 =SUBSTRING(( select distinct ',IsNull(['+rtrim(ProdId)+'],0) as ['+rtrim(ProdId)+']' from OrderDetails for xml path('')),2,8000)
SET #query =
'SELECT EmpId,'+#Product1+' FROM
(
SELECT d.ProdId,m.EmpId,isnull(convert(int,d.Qty),0.0) as oqty
FROM OrderMaster m inner join OrderDetails d on m.OrdId=d.OrdId
)t
PIVOT (SUM(oqty)
FOR ProdId
IN ('+#Product+')) AS pvt'
EXECUTE (#query)
end
Please help me..

JqGrid supports the pivot grid see below link
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:pivotsettings
it loaded only once if you want to change the rows and column at runtime use GridUnload before creating and loading the grid.
jqGrid GridUnload/ GridDestroy

Related

jquery:datatable save button: always gets the original value instead of updated one

I have a jquery:Datatable with a custom Save button like below:
...,
{
text: 'Save',
action: function (e, dt, node, config) {
var json = JSON.stringify(dt.rows().data().toArray());
var dat = $('#MainContent_ddlDate').val();
var cols = ""
dt.columns().header().each(function (e, i) {
var col = jQuery(e).html();
cols += col + ",";
});
$.ajax({
type: "POST",
url: 'Ranking.aspx/SaveRanks',
data: JSON.stringify({ 'tbldata': json, 'cols':cols, 'surveydate': dat }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
window.location.reload();
},
error: function (e) {
Console.log(e);
}
});
}
}
Note that in this datatable, all the columns and rows are created in the back-end dynamically based on some values in SQL DB.
My problem is, when I change a value in a cell and click the save button, it always gets the original value instead of the updated one. I could not find out how to fix this issue.
There is no page refresh occurring, it never hits page_load when "save" is clicked..
Any help would be appreciated.
Regards.
In your success function include this line:
$('#my-datatable').DataTable().ajax.reload();
This reloads the existing table.

ajax call based on the value of 2 input fields to populate jquery autocomplete

I have been stuck with this problem for a while. I would like to pass 2 arguments (the value of 2 input fields of one form) in my ajax call to be used for a jquery autocomplete (the search is based on a mysql query using the values of input1 and input2). I had a few suggestions but so far i have no luck:
here my ajax call trying to pass the 2 arguments input1 and input2. there is no code error showing up but the autocomplete does not work. it is working if i am using only one argument.
function fillbox2(){
$('#input2').autocomplete({
source: function(request, response ){
var frmStr={
input1:$('#input1').val(),
input2:$('#input2').val()
requestTerm: request.term
};
$.ajax({
url: './cgi_temp3.cgi',
dataType: 'json',
data:{data: frmStr},
contentType: "application/json; charset=utf-8",
success: function (data) {
response ($.map( data.matches, function(item){
return {
value: item.info2,
}
}));
}
});
},
minLength: 2,
select: function(event, ui){
$("#prod_term").val(ui.item.value);
return false;
}
});
and here my cgi script that process the MYSQL query
#!/usr/local/bin/python3
import cgi, json
import os
import mysql.connector
def main():
print("Content-Type: application/json\n\n")
form = cgi.FieldStorage()
term2 = form.getvalue('input2')
term1=form.getvalue('input1')
conn = mysql.connector.connect(user='***', password='***', host='localhost', database='***')
cursor = conn.cursor()
qry = """
SELECT name2, info2
FROM table2
join table1 ON
info2_id=information2_id
WHERE name2 LIKE %s AND info2_id=%s
"""
cursor.execute(qry, ('%' + term2 + '%',term1))
where could be the problem?
At first glance I'd say it's possibly a timing issue. The source function isn't going to wait for your ajax call to complete, so you're essentially giving it a blank value. Try initiating the autocomplete inside the ajax success function.
function fillbox2(){
$.ajax({
...
success: function (data) {
...
$('#input2').autocomplete(...);
});
}

jQuery - Add row to datatable without reloading/refreshing

I'm trying add data to DB and show these data in same page using ajax and jQuery datatable without reloading or refreshing page. My code is saving and retrieving data to/from database. But updated data list is not showing in datatable without typing in search box or clicking on table header. Facing same problem while loading page.
Here is my code
//show data page onload
$(document).ready(function() {
catTable = $('#cat_table').DataTable( {
columns: [
{ title: "Name" },
{ title: "Level" },
{ title: "Create Date" },
{ title: "Status" }
]
});
get_cat_list();
});
//save new entry and refresh data list
$.ajax({
url: 'category_save.php',
type: 'POST',
data:{name: name,level: level},
success: function (data) {
get_cat_list();
},
error: function (data) {
alert(data);
}
});
//function to retrieve data from database
function get_cat_list() {
catTable.clear();
$.ajax({
url: 'get_category_list.php',
dataType: 'JSON',
success: function (data) {
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
] );
});
}
});
}
The solution is here - for DataTable server side data source enabled
.draw() will cause your entire datatable to reload, say you set it to show 100 rows, after called .row().add().draw() > datatable will reload the 100 rows again from the server
I wasted an hour trying to find any solution for this very old question, even on DataTable official support there is no good solution suggested ...
My solution is
1- call .row().add()
2- do not call .draw()
3- your row must have an Id identifier to use it as a selector (check the rowId setting of the datatable)
4- after calling .row().add(), the datatable will have the row added to it's local data
5- we need to get this row from datatable object and transform it to HTML using the builtin method .node()
6- we gonna prepend the result HTML to the table :)
All that can be done in two lines of code
var rowData = someRowCreatedByAnAjaxRequest;
myDataTableObject.row.add(rowData);
$("#myTable-dt tbody").prepend(myDataTableObject.row(`tr#${rowData.Id}`).node().outerHTML)
Thanks ☺
From the documentation,
This method will add the data to the table internally, but does not
visually update the tables display to account for this new data.
In order to have the table's display updated, use the draw() method, which can be called simply as a chained method of the row.add() method's returned object.
So you success method would look something like this,
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
]).draw();
});

ASP.NET MVC ajax custom filter and paging

I try to use Datatable in mvc application. I have a custom form to filter values, and load data into table by ajax.
$('#tblProducts').DataTable({
serverSide: true,
bFilter: false,
"oLanguage": {
"sUrl": "/Content/DataTables/languages/Russian.json"
},
"ajax": function (data, callback, settings) {
$.ajax({
url: "/Admin/Product/Products",
type: "POST",
data: $("#searchForm").serializeObject() + "&draw=" + data.draw + "&start=" + data.start + "&length=" + data.length
});
}
});
In controller i pass my viewmodel to filter values and paging info.
But my table didn't show any content.
Controller
public ActionResult Products(ProductSearchViewModel model, int draw, int start, int length){//filtering data...}
json
${"draw":1,"iTotalRecords":1048,"iTotalDisplayRecords":10,"aaData":[["1","1001F","GoodWill","Воздушные","16","0,0008","0,87","False"],["2","1002F","GoodWill","Тормозные колодки","16","0,000928","1,505","False"],["3","1003F","GoodWill","Тормозные колодки","10","0,001716","1,595","True"],["4","1004F","GoodWill","Тормозные колодки","16","0,0008","1,88","True"],["5","1007F","GoodWill","Тормозные колодки","13","0,001804","2,46","True"],["6","1008F","GoodWill","Тормозные колодки","10","0,001716","1,6","True"],["7","1010F","GoodWill","Тормозные колодки","16","0,00096","1,63","True"],["8","1012F","GoodWill","Тормозные колодки","16","0,001494","0,023902","True"],["9","1013F","GoodWill","Тормозные колодки","16","0,0008","0,92","True"],["10","1013FX","GoodWill","Тормозные колодки","16","0,0008","0,93","True"]]}
This json come to client, I can see it in fiddler, but table does not show anything.
And there is no javascript errors in Chrome console.
What shall I do to display data in table?

Populate jqGrid dropdown using beforeShowForm Event

I'm trying to dynamically populate a dropdown when a user is trying to add a new record in a detail jqGrid. Here's what I have so far. It's pulling in the data fine but it just won't set the value to the dropdown. Any help would be greatly appreciated.
beforeShowForm: function(formid) {
var sr = $("#list").jqGrid('selrow');
if (sr) {
// get data from master
var UserID = $("#list").getGridParam('selrow');
var roles = $.ajax({ type: "POST",
url: '<%= ResolveUrl("~/Admin/GetRoles/") %>' + UserID,
dataType: "json",
async: false,
success: function(data) {
}
}).responseText;
// set the field in detail with the value of mnaster
$("#UserID", formid).val(UserID);
// try and populate dropdown
$('#detail').setColProp('Description', { editoptions: { value: roles} });
} else {
// close the add dialog
alert("no row is selected");
}
}
In your first question I explained you how to use dataUrl to generate the contain of the dropdown list dynamically. If you use form editing to modify the grid data you can use beforeInitData instead of beforeShowForm to modify the dataUrl to '<%= ResolveUrl("~/Admin/GetRoles/") %>' + $("#list").jqGrid('selrow') before the form will be filled. In the way you can simplify your code, make the ajax request asynchronous and the question with setting the values to the dropdown control will be solved automatically.

Categories