jQuery url - editurl -> is there also a addurl - javascript

Hi I have a problem in a jquery asp.net project:
I have on one page 2 grids - the main grid is loaded while the second grid is disabled(hidden). When I click on one row in the main grid the second grid is shown then and shows the data if some exist regarding to this row. If there is now data I want to create new data in the second grid. I tried to handle this with url (to get the data), editurl (to modify existing data) which works fine and now I need e.g. a addurl to create new data.
Has anyone an idea to fix this problem because I didn't really found something on the net about this..
onSelectRow: function (id) {
var rid = jQuery('#tblJQGridBereitschaft').jqGrid("getGridParam", "selrow");
if (rid) {
var row = jQuery('#tblJQGridBereitschaft').jqGrid("getRowData", rid);
}
var bs_id = row.ID;
function seturl(bs_id){
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ loadonce: false })
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ datatype: "json" })
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ url: '#Url.Action("GetFahrtkosten", "Bereitschaft")?BS_ID=' + bs_id +'', page: 1 }).trigger('reloadGrid');
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ editurl: '#Url.Action("ModifyFahrtkosten", "Bereitschaft")?BS_ID=' + bs_id, page: 1 }).trigger('reloadGrid');
// Here I need the "addurl"
jQuery("#tblJQGridBereitschaftFahrtkosten").setGridParam({ loadonce: true })
}
seturl(bs_id);
$("#headerFahrtkosten").show();
$("#jqgrid_containerfahrtkosten").show();
},
Thanks for any help or tips!

Related

Ajax jQuery Multiple Step Form instead of reloading div, just append new content

I wonder if it's possible to do this multistep form on one single page, so not reloading the div with the content received from the php file but append it right below..
This is what I've got so far:
$(document).on('submit', '#reg-form', function(){
var ln = $('#submit').val();
var id = $('#id').val();
var data = 'submit='+ln;
$.ajax({
type: 'GET',
url : 'step.php',
dataType : 'html',
data : data,
success : function(data)
{
$('#reg-form').fadeOut(500).hide(function()
{
$('.result').fadeIn(500).show(function()
{
$('.result'+id).append(data);
});
});
}
});
return false;
});
Also I tried to use different divs, with incremental id's to put every content in it's own div. The Problem is, I'm only getting the "second" step, so it's not going through the whole formular.
I guess it's because the form of the first page is still there and all have the same id.. Can anyone help me out here please?
id of element in document should be unique. Change the duplicate id at html source or using javascript
success : function(data) {
// change duplicate `reg-form` `id` to value
// corresponding to `.length` of elements having `id`
// containing `"reg-form"`
$(data).filter("#reg-form")
.attr("id", "reg-form-" + $("[id*='reg-form']").length);
$("#reg-form").fadeOut(500).hide(function() {
$(".result").fadeIn(500).show(function() {
$(".result" + id).append(data);
});
});
}

jquery what the best way to reset every positioning to default?

I have a few thumbnails upon clicked, it will display all the works of the user, for example user 1 have 1 work, user 2 have 6 works. By right i will be showing the div accordingly to how many works the user have. If i click on user 1, it show 1 work, i exit and click on user 2, instead of 6 works it show 1 only, because the function takes on what was set on user1, as i didn't reset.. So i wonder if there is a best practices for resetting the show/hide div back to default upon exit, the only solution i know of now is calling the .show each time the function activates, but doesn't seem to be a good way to do things. Please advise
Example
$(function() {
$(".img_thumb_holder").on('click', function() {
var index = $(this).index(); // get current index of clicked thumbnail, so i can call out the related name from captionArray via same index
// what i did to solve the reseting, forcing it to show out each time the function runs
$(".portfolio_thumbImg_holder").show();
$.ajax({
type: "POST",
dataType: "json",
data: ({id: idArray[index]}), // pass the name of clicked holder into php to query
url: "CMS/PHP/retrieveAuthorWorks.php",
success: function(data) {
console.log("Array consist of " + data)
$('.portfolio_thumbImg_holder img').removeAttr("src");
linksArray=[];
titleArray=[];
descArray=[];
$(".full_image_desc .title").html(data[0].title);
$(".full_image_desc .info").html(data[0].desc);
$('.portfolio_thumbImg_holder img').each(function(index, element) {
if (data[index]) {
linksArray.push("http://localhost/testdatabase/cms/" + data[index].links);
$(element).attr("src", linksArray[index]);
titleArray.push(data[index].title);
$(element).attr("title", titleArray[index]);
descArray.push(data[index].desc);
$(element).attr("desc", descArray[index]);
}
});
// check how many divs without the image data, and hide it
$(".portfolio_thumbImg_holder img:not([src])").parent().hide();
}
});
});
});

Update option total pages with ajax in Jquery Plugin wpaginate

I have a problem with wpaginate Jquery Plugin: https://github.com/websanova/wPaginate . It has total attribute which is total number of records. But I don't know how to make it works properly.
Javascript:
$.get(rootUrl + "js/my_cursostotal.php", {}, function(data){
$('#wPCursos').wPaginate({
theme: 'lightblue',
total: data,
limit: 3,
url: function(i) {
$('#wPCursos').wPaginate('total', data);
loadCursos('action=ajax&page='+ (i+1) );
},
ajax: true
});
});
function loadCursos(str) {
//$("#loader").fadeIn('slow');
$('#cursosTabla').load('index.php?'+str,function() {
//$("#loader").fadeOut('slow');
});
console.log("%s", str);
}
my_cursostotal.php
$cursos_total = $cursos_tabla->total();
echo $cursos_total;
When I delete or add elements elements of the table $cursos_total change, but the total pages are not updated until I click 2 page items.
I have used console.log('%s' data) and I get the correct elements in it, but the wpaginate item doesn't take it until I click two times in pages, then appears the new page or drop a page.
What can I do? It's important for me.
I think that I have to modify the Jquery Plugin, but I have no idea. I have tried, but it's very complicated for me.
I want only how to make to reset the settings of jQuery plugin wpaginate to display properly the number of pages.
You have a demo of the plugin here: http://wpaginate.websanova.com/
Thanks in advance.
I have find some help and I've solved it:
$.get(rootUrl + "js/my_cursostotal.php", {}, function(data){
$('#wPCursos').wPaginate({
theme: 'lightblue',
total: data,
limit: 3,
url: function(i) {
$.get(rootUrl + "js/my_cursostotal.php", {}, function(data){
$('#wPCursos').wPaginate('total', data);
$('#wPCursos').data('_wPaginate').generateLinks();
});
loadCursos('tabla=cursos&action=ajax&page='+ (i+1) );
},
ajax: true
});
});
"$('#wPCursos').data('_wPaginate').generateLinks();" makes the trick.

I need sme help automating jqGrid filters, please

Okay, so in a nutshell, what I need to do is to automatically apply a set of sorting criteria and data filters to the jqGrid when it loads. The intent is that the user will start with about 10 pre-filled filters and then, if they so choose, they can alter those filters or the sorting however they see fit.
So far, with much Google-ing, trial and error and sweat, I have the following working:
-> I can load/save the sort column & sort order in a session cookie.
-> I can load the search dialog with pre-defined search filters. After the grid loads, I can open the modal dialog and see the proper filters and if I click "Find" the appropriate data is posted to the server and the right results are returned to the screen.
The thing that is biting me in the butt right now is, I think, the easy part, but it escapes me. I can't seem to do either of the following:
( A ) The ideal thing would be if I could attach these filters to the grid and it's post data in advance of the initial load so that there is only a single trip to the server.
( B ) The workable solution, though less ideal, would be for the grid to load the first page of the unfiltered data first, and then apply the filters and re-query the server for the filtered data.
Since I can manually click the "find" button today and it works, I thought that "B" would be a good next-step. So, in my gridComplete function, I have the following code:
$('#AccountGrid').clearFilter({gridName:'AccountGrid', pagerName:'AccountPager'});
$('#AccountGrid').addFilter({gridName:'AccountGrid', field:'AccountID', data:1, op:'ne'});
$('#AccountGrid').addFilter({gridName:'AccountGrid', field:'AccountID', data:3, op:'ne'});
// $('#fbox_AccountGrid').searchFilter().search();
// $('#fbox_AccountGrid .ui-search').click();
$('#AccountGrid').trigger('reloadGrid');
NOTE: "clearFilter" and "addFilter" are extension functions I have added to jqGrid to simplify adding and removing filters on the grid. They work exactly as desired at this point.
As you can see with those last three lines of code, I have tried using the built-in function, as well as going after the find button directly and even just forcing the entire grid to refresh. Either way, there is no attempt by the grid to go get new data (I am using Fiddler to watch for it).
What am I doing wrong in trying to force the grid to reload with the new filters?
And, if you know how, can you give me some direction on how to get the initial load of the grid to respect these filters?
TIA
Tony
Here is the full grid configuration (minus the extra columns and some colModel "cruft"):
jQuery('#AccountGrid').jqGrid({
url: '<my URL>',
width: 950,
height: 330,
shrinkToFit: 'true',
datatype: 'json',
mtype: 'POST',
multiselect: true,
multiboxonly: true,
multiselectWidth: 20,
colNames: [
'Account ID'
],
colModel: [
{ name: 'AccountID', index: 'AccountID', sortable: false, hidden:false, search:true }
],
gridComplete: function () {
// add the search criteria to the grid
if (initialLoad == true){
$('#AccountGrid').clearFilter({gridName:'AccountGrid', pagerName:'AccountPager'});
$('#AccountGrid').addFilter({gridName:'AccountGrid', field:'AccountID', data:1, op:'ne'});
$('#AccountGrid').addFilter({gridName:'AccountGrid', field:'AccountID', data:3, op:'ne'});
// $('#fbox_AccountGrid').searchFilter().search();
// $('#fbox_AccountGrid .ui-search').click();
$('#AccountGrid').trigger('reloadGrid');
initialLoad = false;
}
},
jsonReader: {
repeatitems: false,
id: 'AccountID'
},
pager: jQuery('#AccountPager'),
rowNum: 50,
rowList: [10, 15, 25, 50, 75, 100],
onSortCol : function (sortname, indexColumn, sortorder){
$.cookie('AccountGrid_sortname', sortname);
$.cookie('AccountGrid_sortorder' , sortorder);
},
sortname : $.cookie('AccountGrid_sortname') ? $.cookie('AccountGrid_sortname') : 'AccountID',
sortorder: $.cookie('AccountGrid_sortorder') ? $.cookie('AccountGrid_sortorder') : 'asc',
viewrecords: true,
imgpath: ''
});
$('#AccountGrid').jqGrid('navGrid','#AccountPager',
{ view: false, add: false, edit: true, del: false,
alertcap:'No Account Selected',
alerttext: 'Please select an Account from the grid before performing this operation.',
editfunc: showAccountEditDialog },
{}, // default settings for edit
{}, // default settings for add
{}, // delete
{closeOnEscape: true, multipleSearch: true, closeAfterSearch: true }, // search options
{}
);
And, by request, here is the code I have for add/clear filter:
/*
This is a grid extension function that will insert a new filter criteria
on the specified grid with the provided field, operation & data values
*/
(function ($) {
jQuery.jgrid.addSearchFilter =
{
// get/set the parameters
addFilter: function (options) {
var grid = $(this);
// get offset values or assign defaults
var settings = $.extend({
gridName: '',
field: '',
data: '',
op: ''
}, options || {});
// get the column model object from the grid that matches the provided name
var colModel = grid.getGridParam('colModel');
var column;
for (var i = 0; i < colModel.length; i++) {
if (colModel[i].name == options.field){
column = colModel[i];
break;
}
}
colModel = null;
if (column){
// if the last filter has a value, we need to create a new one and not overwrite the existing ones
if ($('#fbox_' + options.gridName + ' .sf .data input').last().val()){
$('#fbox_' + options.gridName).searchFilter().add();
}
// assign the selections to the search dialog
$('#fbox_' + options.gridName + ' .sf .fields select.field').last().val(column.index).change();
$('#fbox_' + options.gridName + ' .sf .data input').last().val(options.data);
$('#fbox_' + options.gridName + ' .sf .ops select.default').last().val(options.op).change();
}
}
}
})(jQuery);
jQuery.fn.extend({ addFilter: jQuery.jgrid.addSearchFilter.addFilter });
/*
This is a grid extension function that will clear & reset the filter criteria
*/
(function ($) {
jQuery.jgrid.clearSearchFilter =
{
// get/set the parameters
clearFilter: function (options) {
var grid = $(this);
// get offset values or assign defaults
var settings = $.extend({
gridName: '',
pagerName: ''
}, options || {});
// clear the filters and "pop" the dialog to force the HTML rendering
$('#fbox_' + options.gridName).searchFilter().reset();
$('#' + options.pagerName + ' .ui-icon-search').click();
$('#fbox_' + options.gridName).searchFilter().close();
}
}
})(jQuery);
jQuery.fn.extend({ clearFilter: jQuery.jgrid.clearSearchFilter.clearFilter });
First of all because you don't post the code which define the jqGrid I make some assumption myself. I try to base on indirect information from your question.
1) I suppose that you use server side datatype parameter of jqGrid like 'json' or 'xml'.
2) You don't use loadonce:true parameter. In general if would be possible to make server reload from the grid having loadonce:true, but in the case you have to reset the value of datatype parameter to initial value (one from the value 'json' or 'xml').
The following three old answer: this (in case of single value searching) and this (in case of advanced searching or the toolbar searching with additional parameter stringResult:true) will give you enough information about setting the searching filters and reloading the grid corresponds to the new filters. Another answer shows how to clear the searching filter if it is no more needed.
Loading of the grid at the first time with the filters is another question. It can be very easy implemented. You should just use datatype:"local" instead of datatype:"json" or datatype:"xml" which you really need. In the case the url parameter of jqGrid will be just ignored at the first load and jqGrid send no request to the server. Then you set the filters like you as need and only then use $("#youGridId").trigger("reloadGrid");
The reason why the reloadGrid didn't work in your case I could not know exactly, but I suppose that you didn't set the search:true parameter of the jqGrid which one confuses frequently with the _search property of the postData parameter (see here).

How to disable tabs in JqGrid at runtime?

Two Default Grids Defenition:
initialise(){
$("#ExpenseTable").jqGrid({
datatype : "local",
mtype : 'GET',
colModel : [ {name:'expnsId',label:'ID', width:150 },
{name:'userName',label:'NAME', width:150 },
{name:'catName',label:'CATEGORY', width:150 },
{name:'date',label:'DATE', width:150 },
{name:'amount',label:'AMOUNT', width:150 },
{name:'status',label:'STATUS', width:150 }],
pager : '#ExpPager',
rowNum : 10,
rowList : [ 10, 20, 30 ],
sortname : 'invid',
sortorder : 'desc',
viewrecords : true,
autowidth : false,
caption : 'Expenses Details',
onSelectRow : function(expnsId) { dispExpensData(expnsId); }
});
$("#tabs").tabs();
getTokens();//Gets the tokens for the logged in user.
refreshExpenseGrid();//Populates data to the grid
dispLeaveGrid();// It ll call the next default grid
}
}
$("#LeaveTable").jqGrid({
datatype : "local",
mtype : 'GET',
colModel : [ {name:'leaveId',label:'ID', width:150 },
{name:'userName',label:'NAME', width:150 },
{name:'fdate',label:'DATE', width:150 },
{name:'tdate',label:'DATE', width:150 }
{name:'status',label:'STATUS', width:150 }],
pager : '#ExpPager',
rowNum : 10,
rowList : [ 10, 20, 30 ],
sortname : 'invid',
sortorder : 'desc',
viewrecords : true,
autowidth : false,
caption : 'Leave Applications',
onSelectRow : function(leaveId) { displeaveData(leaveId); }
});
refreshLeaveGrid();//Populates data to the grid
securedUI();//This ll call the below function, to check whether the remaining tabs can be visible or not
Secured UI Function:
function securedUI(){
var secToken = "DELETEUSER";
if(!checkRoleToken(secToken)){//If users dont have token to delete user, the buttons ll be disabled
$('#expDelete').attr('disabled', 'disabled');
$('#lveDelete').attr('disabled', 'disabled');
$('#delUser').attr('disabled', 'disabled');
$('#roleDel').attr('disabled', 'disabled');
$('#tokenDel').attr('disabled', 'disabled');
}
var secToken= "VIEWUSER";
if(checkRoleToken(secToken)){
showUserdetails();//3rd Grid Defn:Contains the table definition for user grid.
initialiseRole();//4th Grid Defn: Role grid
showtokens();//5th Grid Defn: token grid
}
Check Token:
function checkRoleToken(newToken){
for( var i = 0; i<tokens.length; i++ ){
var token = tokens[i];//Tokens is like cache, which contains all the tokens that are assigned for the current user.
if(newToken == token.tokenName){
return true;
}
}
return false;
}
The html page:
<script type="text/javascript">
$(document).ready(function() {
initialise();
});
</script>
The LeaveTable is 2nd grid and i have 3 more grids. But i dont want to show them to all of the users, instead admin users should able to see them. Tokens are the key to find the user have the right to do any operation in the Application. Tokens, that are assigned for the user will be loaded to a client-Side Cache like Array tokens.
Every function like ADD, DELETE, UPDATE & VIEW have their tokens at the start of the function that stored in a variable. That token variable will sent to CheckToken() as argument. There it will check that token against the token cache. It ll return true or false. The operation will cancelled or continued according to that result.
In the above code, at the end of the LeaveTable grid defenition, you can see a function call securedUI();. Inside that function i am doing two things. 1.Disabling Delete Buttons, 2.Disabling the 3rd, 4th & 5th grids, for those who dont have tokens DELETEUSER & VIEWUSER.
Actually what i am getting now is, the 3rd, 4th & 5th grids are not getting displayed for those who have token VIEWUSER. Look at the functions securedUI() & checkToken(), what they should do!!! securedUI() have VIEWUSER token and the current user also, so the checkToken() should return true, so it should get into the if block and execute the functions calls inside the if block. But its not doing it. I cant able to get any clue about where i am going wrong.
So, i turned on the firebug and checked it step by step. Magically, now its going into the if block and shows the grid for admin users. Now i felt that it worked then i turned turned off the firebug and reloaded the page again. Ooops, again that 3 remaining grids are not displaying. Can you now able to get an idea about my problem!!!
Any suggestions!!!
It seems to me that you should just place all your JavaScript code inside of jQuery(document).ready handle: jQuery(document).ready(function() {/* place your code here */});
If you do use this handle, please post more full code of your example inclusive full HTML code. You can reduce the code example to have example more compact. Important is only that the problem stay in the code and everyone can reproduce the problem.

Categories

Resources