postData not passing any parameters! - jqgrid

I'm not able to see any parameters value passing to server in firebug. Here is the code.
//BuyBackGridInit() start
function BuyBackGridInit(tabID){
$('table[id$="'+tabID+'_BuyBackGrid"]').jqGrid({
url :'/Controls/Advertiser/BuyBackControlNew.ascx.ashx?action=getBuyBackData',
datatype: 'json',
mtype: 'POST',
height:'100%',
width:'100%',
colNames: result.colNamesData,
colModel: result.colModelData,
postData: {
advertiserID: function() { return $('#advertiser_id').text(); },
CampaignsDdlSelectedValue: function() { return $('select[id$="CampaignDdl"] option:selected').val(); },
startDate: function() { return $('input[id$="'+tabID+'_FromCalBuyBack_CalendarTbx"] ').val(); },
endDate: function() { return $('input[id$="'+tabID+'_ToCalBuyBack_CalendarTbx"] ').val(); }
},
rowNum : 100,
shrinkToFit :false,
altRows: true,
altclass:'altRow',
autowidth: true,
multiselect: true,
gridComplete:function (){
var recs = parseInt( $('table[id$="'+tabID+'_BuyBackGrid"]').getGridParam("records"),10);
if (recs == 0){
$('div[id$="'+tabID+'_NoDataFoundBuyBackdiv"]').show();
$('input[id$="AddToCartBtn"]').hide();
$('input[id$="BuyBackDownloadBtn"]').hide();
}
else {
$('div[id$="'+tabID+'_NoDataFoundBuyBackdiv"]').hide();
$('input[id$="AddToCartBtn"]').show();
$('input[id$="BuyBackDownloadBtn"]').show();
}
},
serializeGridData: function (data){
return $.toJSON(data);
}
});//end of jQuery("#BuyBackGrid").jqGrid()
}//BuyBackGridInit() End
Thanks,
A

You current implementation of serializeGridData just remove all functions parameters from the postData. So you should either extend data parameter inside of serializeGridData instead of the usage of postData. Another way is to modify serializeGridData to the following:
serializeGridData: function (data){
var propertyName, propertyValue, dataToSend = {};
for (propertyName in data) {
if (data.hasOwnProperty(propertyName)) {
propertyValue = data[propertyName];
if ($.isFunction(propertyValue)) {
dataToSend[propertyName] = propertyValue();
} else {
dataToSend[propertyName] = propertyValue
}
}
}
return JSON.stringify(dataToSend);
}
In the code above we enumerate all properties and call all functions explicitly. Moreover I prefer to use JSON.stringify function from json2.js. The function will be native implemented in many web browsers.
See the demo here.

Related

if else condition in ajax not returning boolean

I'm using ajax and successfully getting the response. I'm unable to understand, why if-else condition is not returning boolean value as expected. Not sure, if I'm using the return in right place or not. Need help.
validateEverPresentRowWidgetValue: function (datafield, value, rowValues) {
if ((!value)) {
$.alert({
content: 'Please select Date!',
btnClass: 'btn-warning',
boxWidth: '30%',
title: 'Missed something!',
type: 'orange',
typeAnimated: true,
useBootstrap: false
});
return false; //Works fine
} else if (value) {
$.ajax({
url: 'checkForLeave.php',
dataType: 'json',
method: 'post',
data: {date: value},
success: function (response) {
if (response.length > 0) {
$.confirm({
title: 'Confirm!',
content: 'This date is NOT allowed! <br> Reason:' + response[0].comments,
boxWidth: '30%',
typeAnimated: true,
useBootstrap: false,
btnClass: 'btn-warning',
type: 'orange',
buttons: {
confirm: function () {
return true; //Problem in return
},
cancel: function () {
return false; //Problem in return
}
}
});
} else {
return true;
}
},
error: function (response) {
return false;
}
});
}
}

jqGrid using inlineNav refresh not working with extraparams

After following the solution in a previous post, I have found that the jqGrid refresh after add/edit with the inlineNav using the successfunc does not work if extraparams is present.
Here's my code:
var editOptions = {
keys: true,
successfunc: function () {
alert('success');
var $self = $(this);
setTimeout(function () {
alert('refreshing');
$self.setGridParam({ datatype: 'json' });
$self.trigger("reloadGrid");
}, 500);
}
.jqGrid('inlineNav', {
addParams: {
useDefValues: true,
addRowParams:
{
editOptions,
extraparam: {
userId: function () {
return currentUserId;
},
companyId: function () {
return currentCompanyId;
}
}
}
},
editParams: {
editOptions
}
I have tried different combinations of where the editOptions is placed, but no luck.
You placed extraparam in the wrong place. It should be the property of editOptions.
UPDATED:
var reloadGridFunc = function () {
alert('success');
var $self = $(this);
setTimeout(function () {
alert('refreshing');
$self.setGridParam({ datatype: 'json' });
$self.trigger("reloadGrid");
}, 500);
};
.jqGrid('inlineNav', {
addParams: {
useDefValues: true,
addRowParams: {
// here are editOption used for Add
keys: true,
successfunc: reloadGridFunc,
extraparam: {
userId: function () {
return currentUserId;
},
companyId: function () {
return currentCompanyId;
}
}
}
},
editParams: {
// here are editOption used for Edit
keys: true,
successfunc: reloadGridFunc
}
});
Ok - I found what I was doing wrong. It was actually in both parts of my code above. First, I changed:
function successFunc() {
var $self = $(this);
setTimeout(function () {
$self.setGridParam({ datatype: 'json' });
$self.trigger("reloadGrid");
}, 500);}
I got rid of the var editOptions, which included the keys and successfunc parameters inside it. This apparently was conflicting with the successfunc call in the addParams part of the inlineNav method. So here's what the parameters section looks like now:
.jqGrid('inlineNav', {
addParams: {
addRowParams:
{
keys: true,
extraparam:
{ userId: currentUserId,
companyId: currentCompanyId
},
successfunc: successFunc
}
},
editParams: {
successfunc: successFunc
}
});
So now when I either add or edit an inline record, the refresh happens when the successfunc is called. Hope this helps someone else in the future. Thanks #Oleg for the initial help with this.

Issue in JQuery Confirmation Dialog inside form submit

In a JQuery dialog I have four fields. When I click on Save button I needs to check and validate the following
Validate all required fields ( On submit of form using validate.js and unobstrusive.js )
Check the value of dropdown and if it is of a partcular type ie (Redundant), Show user a confirmation dialog.
If the user confirm by pressing Yes, then close the confirmation dialog and call Ajax
But the problem is when I confirm by clicking Yes button on confirmation dialog, the dialog closes but the execution is not going down.
ie, Serializing the form data and make an Ajax call to call the webservice.
Please can anyone help.
$(function () {
$('form').submit(function () {
$('#result').html(" ");
var redunt = null;
redunt = $(ClientCrud_StatusCodeId).find('option:selected').text();
if ($(ClientCrud_StatusCodeId).find('option:selected').text() == "Redundant") {
$('#clientRedundantMessage2').html("Client once made redundant cannot be reactivated. Are you sure ?");
$("#RedundantMessage2").dialog(
{
autoOpen: false,
height: 170,
width: 420,
modal: true,
resizable: false,
title: "Confirmation for Redundant",
Content: "Fields cannot be left blank.",
buttons: {
"Yes": function () {
redunt = "Active";
$('#RedundantMessage2').dialog('close');
},
"No": function () {
$(this).dialog("close");
return false;
}
}
}) //.dialog("widget").draggable("option", "containment", "none");
$("#RedundantMessage2").dialog("open");
}
if ($(this).valid())
{
debugger;
if (redunt == "Active") {
$.ajax({
url: this.action,
type: this.method,
async: false,
cache: false,
data: $(this).serialize(),
error: function (request) {
$("#result").html(request.responseText);
// event.preventDefault();
},
success: function (result) {
if (result == "success") {
$.ajax({
url: "/Client/ClientGrid",
type: 'POST',
data: { "page": 0 },
datatype: 'json',
success: function (data) {
$('#grid').html(data);
},
error: function () {
alert('Server error');
}
});
$('#myEditClientDialogContainer').dialog('close');
$('#myEditClientDialogContainer').remove()
}
else {
clearValidationSummary();
var a = '<ul><li>' + result + '</li></ul>';
$('#result').html(a);
}
}
});
}
}
$("#griderrormsg1 li").hide().filter(':lt(1)').show();
return false;
});
editallowed = true;
});
I think you have a issue with the sequence of code, when the function $("#RedundantMessage2").dialog( ...... ); execute don't wait for the user response in this case "yes" or "no" so... your flag redunt = "Active" don't make sense.
the buttons option has function that execute when the opcion is choosen, so you must call a function to execute the post
$(function () {
$('form').submit(function () {
$('#result').html(" ");
var redunt = null;
redunt = $(ClientCrud_StatusCodeId).find('option:selected').text();
if ($(ClientCrud_StatusCodeId).find('option:selected').text() == "Redundant") {
$('#clientRedundantMessage2').html("Client once made redundant cannot be reactivated. Are you sure ?");
$("#RedundantMessage2").dialog(
{
autoOpen: false,
height: 170,
width: 420,
modal: true,
resizable: false,
title: "Confirmation for Redundant",
Content: "Fields cannot be left blank.",
buttons: {
"Yes": function () {
redunt = "Active";
trySend();
$('#RedundantMessage2').dialog('close');
},
"No": function () {
$(this).dialog("close");
return false;
}
}
}) //.dialog("widget").draggable("option", "containment", "none");
$("#RedundantMessage2").dialog("open");
}
$("#griderrormsg1 li").hide().filter(':lt(1)').show();
return false;
});
editallowed = true;
});
the other js function
function trySend(){
if ($('#IdOfYourForm').valid())
{
debugger;
if (redunt == "Active") {
$.ajax({
url: this.action,
type: this.method,
async: false,
cache: false,
data: $(this).serialize(),
error: function (request) {
$("#result").html(request.responseText);
// event.preventDefault();
},
success: function (result) {
if (result == "success") {
$.ajax({
url: "/Client/ClientGrid",
type: 'POST',
data: { "page": 0 },
datatype: 'json',
success: function (data) {
$('#grid').html(data);
},
error: function () {
alert('Server error');
}
});
$('#myEditClientDialogContainer').dialog('close');
$('#myEditClientDialogContainer').remove()
}
else {
clearValidationSummary();
var a = '<ul><li>' + result + '</li></ul>';
$('#result').html(a);
}
}
});
}
}
}

jqGrid Setting id of new added Row intoGrid

jQuery.extend(
jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" }, //form editor
reloadAfterSubmit: true
// afterSubmit: function (response, postdata) {
// return [true, "", $.parseJSON(response.responseText).d];
//}
});
$.extend($.jgrid.defaults, {
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
ajaxRowOptions: { contentType: "application/json", type: "POST" },
//row inline editing
serializeGridData: function(postData) { return JSON.stringify(postData); },
jsonReader: {
repeatitems: false,
id: "0",
cell: "",
root: function(obj) { return obj.d.rows; },
page: function(obj) { return obj.d.page; },
total: function(obj) { return obj.d.total; },
records: function(obj) { return obj.d.records; }
}
});
$("#grantlist").jqGrid({
url: 'webservice.asmx/GetGrant',
colNames: ['ID', 'Name', 'Title'],
colModel: [
{ name: 'ID', width: 60, sortable: false },
{ name: 'name', width: 210, editable: true },
{ name: 'title', width: 210, editable: true }
],
serializeRowData: function(data) {
var params = new Object();
params.ID = 0;
params.name = data.name;
params.title = data.title;
return JSON.stringify({ 'passformvalue': params, 'oper': data.oper, 'id': data.id });
},
mtype: "POST",
sortname: 'ID',
rowNum: 4,
height: 80,
pager: '#pager',
editurl: "webservice.asmx/ModifyGrant"
});
$("#grantlist").jqGrid('navGrid', '#pager', { add: false, edit: false, del: false, refresh: false, search: false });
$("#grantlist").jqGrid('inlineNav', '#pager');
//this is my server code
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public JQGrid<GrantComittee> GetGrantComittee(int? page, int? rows, string sidx, string sord, bool _search)
{
JQGrid<GrantComittee> jqgrid = new JQGrid<GrantComittee>();
List<GrantComittee> data = GetGComittee();
jqgrid.records = data.Count; //total row count
jqgrid.total = (int)Math.Ceiling((double)data.Count / (double)rows); //number of pages
jqgrid.page = page.Value;
//paging
data = data.Skip(page.Value * rows.Value - rows.Value).Take(rows.Value).ToList();
foreach(GrantComittee i in data)
jqgrid.rows.Add(i);
return jqgrid;
}
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public int ModifyGrantComittee(GrantComittee passformvalue, string oper, string id)
{
if (String.Compare(id, "_empty", StringComparison.Ordinal) == 0 ||
String.Compare(oper, "add", StringComparison.Ordinal) == 0)
{
GrantComittee data = new GrantComittee();
List<GrantComittee> set = new List<GrantComittee>();
set = (List<GrantComittee>)Session["grantcomittee"];
data = passformvalue;
data.ID = set.Max(p => p.ID) + 1;
set.Add(data);
Session["grantcomittee"] = set;
return data.ID;
}
else if (String.Compare(oper, "edit", StringComparison.Ordinal) == 0)
{
// TODO: modify the data identified by the id
return 0;
}
else if (String.Compare(oper, "del", StringComparison.Ordinal) == 0)
{
// TODO: delete the data identified by the id
return 0;
}
return 0;
}
I am using JqGrid to retrieve and add new records to database. So far i have been able to retrieve and add new items to the DB, I am using "json". I do get in the response {"d": "5"} for the id of the newly created row in the DB. However the new id does not display in the grid.
How can I update that value to new added row?
In the most cases you don't need to do anything because of default setting reloadAfterSubmit: true. It means that the full grid will be reloaded from the server after the user add new row or modify an existing one.
If you want use reloadAfterSubmit: false setting and the server returns the id of the new created row in the response you need implement afterSubmit callback function which will decode the server response and return it for the usage of by jqGrid. The corresponding code could be about the following:
afterSubmit: function (response, postdata) {
return [true, "", $.parseJSON(response.responseText).d];
}
You can define the callback by overwriting the default parameters $.jgrid.edit (see here and here).
I am using 'inlinNav' and after adding a new row i was not getting the grid to reload. The solution I found was to add parametes to the 'inlineNav' declaration. So I end up with the code i am providing as reference:
$("#grantlist").jqGrid('inlineNav', '#pager', { addParams: { position: "last", addRowParams: {
"keys": true, "aftersavefunc": function() { var grid = $("#grantlist"); reloadgrid(grid); }
}
}, editParams: { "aftersavefunc": function() { var grid = $("#grantlist"); reloadgrid(grid); } }
});
function reloadgrid(grid) {
grid.trigger("reloadGrid");
}
I was using more than one grid that is why i pass a grid parameter to the reload function.

How to dynamically change event sources?

I am using the jQuery FullCalendar plug-in. I want to load initially the calendar with events as an array. I am doing this like:
events: <%= Model.Events %>
or
eventSources: [{
events: <%= Model.Events %>
}]
Both ways work fine. I am using MVC 3.0 and <%= Model.Events %> returns an array of events in JSON format.
I want to use the events array ONLY for the initial loading of the calendar. Later, every times events are needed to be fetched, I want my events to be loaded using the url '/Calendar/Events'.
How can be this implemented?
I tried difference scenarios with addEventSource/removeEventSource in the viewDisplay callback, but nothing worked fine for me.
.fullCalendar( {
eventSources : [ {
url : '/Calendar/Events',
type : 'GET'
} ],
viewDisplay : function( event ) {
// assuming this will point to the full calendar,
// might have to do something silly like
// $( '#myCal' ).fullCalendar( 'refetchEvents' );
this.refetchEvents();
}
} );
I know it's a very old question but I needed this right now. The answer wasn't here but I found it in another question.
Here what is solution.
My primary source of events is this(this is the events source from the default examples of Fullcalendar):
events: function(start, end, callback) {
$.ajax({
type: 'POST',
url: 'myurl',
dataType:'xml',
crossDomain: true,
data: {
// our hypothetical feed requires UNIX timestamps
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
'acc':'2',
},
success: function(doc) {
var events = [];
var allday = null; //Workaround
var Editable = null; //Workaround
$(doc).find('event').each(function()
{
if($(this).attr('allDay') == "false") //Workaround
allday = false; //Workaround
if($(this).attr('allDay') == "true") //Workaround
allday = true; //Workaround
if($(this).attr('editable') == "false") //Workaround
Editable = false; //Workaround
if($(this).attr('editable') == "true") //Workaround
Editable = true; //Workaround
events.push({
id: $(this).attr('id'),
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end'),
allDay: allday,
editable: Editable
});
});
//calendar.fullCalendar( 'addEventSource', othersources.folgas );
//calendar.fullCalendar( 'addEventSource', othersources.ferias );
//calendar.fullCalendar('refetchEvents');
callback(events);
}
});
}
Now i needed it to add more sources and to do this ouside the calendar (next to the date variables from fullcalendar examples) i made a variable like the code above, but with ajax calls similar to my primary: )
var othersources = {
anothersource: {
events: function(start, end, callback) {
$.ajax({
type: 'POST',
url: 'myurl',
data: {
// our hypothetical feed requires UNIX timestamps
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
'acc':'7',
},
success: function(doc) {
var events = [];
var allday = null; //Workaround
var Editable = null; //Workaround
$(doc).find('event').each(function()
{
if($(this).attr('allDay') == "false") //Workaround
allday = false; //Workaround
if($(this).attr('allDay') == "true") //Workaround
allday = true; //Workaround
if($(this).attr('editable') == "false") //Workaround
Editable = false; //Workaround
if($(this).attr('editable') == "true") //Workaround
Editable = true; //Workaround
events.push({
id: $(this).attr('id'),
title: $(this).attr('title'),
start: $(this).attr('start'),
end: $(this).attr('end'),
allDay: allday,
editable: Editable
});
});
callback(events); //notice this
}
});
},
cache: true,
//error: function() { alert('something broke with courses...'); },
color: 'green', //events color and stuff
textColor: 'white',
//className: 'course'
}
}
Now, he build diffrent sources and use like this both...
eventSources: [ othersources.anothersource ],
viewDisplay: function(view) {
if (view.name == 'month'){
calendar.fullCalendar( 'addEventSource', othersources.anothersource );
//calendar.fullCalendar('refetchEvents');
//Notice i'm not doing the refetch events. And its working for me. but i'm calling thi elsewhere, every time i make an action. So you must figure it out ;)
}
Link to above solution
And another way i found on github.
Basically the problem was that I can't change data parameters after calendar initialization. For events this worked:
events: {
url : '',
type: 'POST',
data: function () {
return {
action: 'view',
search_text: search_text
};
},
error: function() {
alert('there was an error while fetching events!');
},
color: '#31b0d5', // a non-ajax option
textColor: '#fff;', // a non-ajax option
},
for resources it didnt so I had to make like that:
resources: function(callback) {
var view = $("#calendar").fullCalendar("getView");
$.ajax({
url: "",
type: 'POST',
dataType: "json",
cache: false,
data: {
start : view.start.format(),
end : view.end.format(),
timezone : view.options.timezone,
action : 'projects_employees',
search_text: search_text
}
}).then(function(resources) {
callback(resources);
})
},
Simple ways like that do not work cuz are static and couldn't be changed after init:
events: {
url: '',
type: 'POST',
data: {
action: 'view',
search_text: search_text
}
},
resources: {
url: '',
type: 'POST',
data: {
action: 'projects_employees',
search_text: search_text
}
}
Here is the github link. Replied by peon501.
After to many try, i did solve my problem with use first part (stackoverflow) codes. The key for me defiying eventSource with "var" key and use it like this
//...
eventSources: [ othersources.anothersource ] ,
//...
I have collected all the data in a php file the way I want it. And the output of this page was a javascript with this
header('Content-Type: text/javascript');
$fromDB ="";
$sources = "sources = [";
foreach ($events as $value) { // value is source name
$fromDB .= "var $value = {
url: path + 'fetchEvents.php',
method: 'GET',
extraParams: {
value: $value,
code: new URLSearchParams(window.location.search).get('code'),
},
failure: function(error) {
console.log(error);
Swal.fire('Error!', '', 'error');
},
};
";
$sources .= $value. " ";
}
$sources .= " ];";
// this $sources give me
// sources = [anothersource ,othersource ,anothersource2 ];
This make like this
var anothersource = {
url: path + 'fetchEvents.php',
method: 'GET',
extraParams: {
value: $value,
code: new URLSearchParams(window.location.search).get('code'),
},
failure: function(error) {
console.log(error);
Swal.fire('Error!', '', 'error');
},
};
var othersource = {
url: path + 'fetchEvents.php',
method: 'GET',
extraParams: {
value: $value,
code: new URLSearchParams(window.location.search).get('code'),
},
failure: function(error) {
console.log(error);
Swal.fire('Error!', '', 'error');
},
};
var anothersource2 = {
url: path + 'fetchEvents.php',
method: 'GET',
extraParams: {
value: $value,
code: new URLSearchParams(window.location.search).get('code'),
},
failure: function(error) {
console.log(error);
Swal.fire('Error!', '', 'error');
},
};
sources = [anothersource ,othersource ,anothersource2 ];
.fullCalendar( {
eventSources : sources , // here, we use dynamic eventsources
viewDisplay : function( event ) {
// assuming this will point to the full calendar,
// might have to do something silly like
// $( '#myCal' ).fullCalendar( 'refetchEvents' );
this.refetchEvents();
}
} );
I added the main javascript file, which will do all the operations, at the bottom of this php file.
//...
$file = "my/fullcalender/initjavascript/file.js"
file_get_contents($file) . PHP_EOL;
//...
This code opens the javascript file in the $file path and takes whatever is in it and adds it to this file.
I hope that will be useful.

Resources