processAjaxOnInit: is set to "false" but Ajax is still called - tablesorter

I'm preloading my table using PHP and then have processAjaxOnInit: false in my config. What happens is that the call to my Ajax url is still made and instead of appending rows to the table it wipes out the rows that are there. I'm assuming that it's still making the call to get the total number of rows. Can I set this on page load and completely bypass calling the Ajax url?
Thanks
.tablesorterPager({
container: $(".pager"),
ajaxUrl : '/documents_table_data.php?page={page}&size={size}&{filterList:filter}&{sortList:column}',
// use this option to manipulate and/or add additional parameters to the ajax url
customAjaxUrl: function(table, url) {
// manipulate the url string as you desire
//url += '&archive=<?php echo $_GET[archive] ?>&wor=<?php echo $_GET[wor] ?>';
// trigger a custom event; if you want
$(table).trigger('changingUrl', url);
// send the server the current page
return url;
},
ajaxError: null,
ajaxObject: {
dataType: 'json'
},
ajaxProcessing: function(data){
if (data && data.hasOwnProperty('rows')) {
var r, row, c, d = data.rows,
total = data.total_rows,
headers = data.headers,
rows = [],
len = d.length;
for ( r=0; r < len; r++ ) {
row = [];
for ( c in d[r] ) {
if (typeof(c) === "string") {
row.push(d[r][c]);
}
}
// is there a way to do that here when it pushes the row onto the array
// or perhaps there is another funtion you have implemented that will let me do that
rows.push(row);
}
return [ total, rows, headers ];
}
},
// Set this option to false if your table data is preloaded into the table, but you are still using ajax
processAjaxOnInit: false,
output: '{startRow} to {endRow} ({totalRows})',
updateArrows: true,
page: 0,
size: 10,
savePages: true,
storageKey: 'tablesorter-pager',
pageReset: 0,
fixedHeight: false,
removeRows: false,
countChildRows: false,
// css class names of pager arrows
cssNext : '.next', // next page arrow
cssPrev : '.prev', // previous page arrow
cssFirst : '.first', // go to first page arrow
cssLast : '.last', // go to last page arrow
cssGoto : '.gotoPage', // page select dropdown - select dropdown that set the "page" option
cssPageDisplay : '.pagedisplay', // location of where the "output" is displayed
cssPageSize : '.pagesize', // page size selector - select dropdown that sets the "size" option
// class added to arrows when at the extremes; see the "updateArrows" option
// (i.e. prev/first arrows are "disabled" when on the first page)
cssDisabled : 'disabled', // Note there is no period "." in front of this class name
cssErrorRow : 'tablesorter-errorRow' // error information row
});

I just added a pager option named initialRows (currently only available in the master branch). When processAjaxOnInit is false and this option is set, no initial ajax call to the server is done (demo):
$(function(){
$('table').tablesorter({
widgets: ['pager'],
widgetOptions : {
pager_processAjaxOnInit: false,
pager_initialRows: {
// these are both set to 50 initially
// the server can return different values
// and the output will update automatically
total: 50,
filtered: 50
},
// other ajax settings...
}
});
});

Related

Cannot insert data by pressing Enter in Combogrid after selection

I am using a combogrid for load data to insert into datagrid. I call the insert data to datagrid in onSelect. Thats mean when i select any data or press down key to scroll all my data then those rows will be selected any inserted automatically . But i want to look through the rows but only when i press inter then the selected row will be inserted.
I am trying this by using KeyUp function. But this wont working.
This is my previous code:
Combogrid add to row
function combogridData() {
var g = $('#itemListGrid').combogrid('grid'); // get datagrid object
var r = g.datagrid('getSelected'); // get the selected row
$('#itemListGrid').keyup(function(e){
if(e.keyCode == 13)
{
addrowtogrid(r);
}
});
$('#itemListGrid').combogrid('clear');
}
My Combogrid :
<select id="itemListGrid" class="easyui-combogrid" style="width:100%" data-options="
panelWidth: 600,
loader: myloader,
mode: 'remote',
idField: 'book_id',
textField: 'name',
method: 'get',
value: '',
columns: [[
{field:'book_id',title:'Item ID',width:'7%'},
{field:'name',title:'Book Name',width:'48%'},
{field:'retail',title:'retail',width:'5%',align:'right',hidden:true},
{field:'local_sale',title:'local',width:'7%',align:'right'},
{field:'whole_sale',title:'Whole',width:'8%',align:'right'},
{field:'isbn',title:'ISBN',width:'15%'},
{field:'authors',title:'Authors',width:'15%'},
]],
fitColumns: true,
labelPosition: 'top',
onSelect:combogridData ">
I am trying by using this code :
function combogridData() {
var g = $('#itemListGrid').combogrid('grid'); // get datagrid object
var r = g.datagrid('getSelected'); // get the selected row
$('#itemListGrid').keyup(function(e){
if(e.keyCode == 13)
{
addrowtogrid(r);
}
});
$('#itemListGrid').combogrid('clear');
}
I got My Own solution.
don't need to add onSelect anymore.
Just added
$('#itemListGrid').combogrid('textbox').bind('keyup', function(e){
if (e.keyCode == 13){ // when press ENTER key, accept the inputed value.
var g = $('#itemListGrid').combogrid('grid'); //get the combogrid
var r = g.datagrid('getSelected'); //get selected value
addrowtogrid(r); //add to another datagrid
}
});
under JQuery document.ready().
It's working perfectly. Thanks.

Full-featured autocomplete widget for Dojo

As of now (Dojo 1.9.2) I haven't been able to find a Dojo autocomplete widget that would satisfy all of the following (typical) requirements:
Only executes a query to the server when a predefined number of characters have been entered (without this, big datasets should not be queried)
Does not require a full REST service on the server, only a URL which can be parametrized with a search term and simply returns JSON objects containing an ID and a label to display (so the data-query to the database can be limited just to the required data fields, not loading full data-entities and use only one field thereafter)
Has a configurable time-delay between the key-releases and the start of the server-query (without this excessive number of queries are fired against the server)
Capable of recognizing when there is no need for a new server-query (since the previously executed query is more generic than the current one would be).
Dropdown-stlye (has GUI elements indicating that this is a selector field)
I have created a draft solution (see below), please advise if you have a simpler, better solution to the above requirements with Dojo > 1.9.
The AutoComplete widget as a Dojo AMD module (placed into /gefc/dijit/AutoComplete.js according to AMD rules):
//
// AutoComplete style widget which works together with an ItemFileReadStore
//
// It will re-query the server whenever necessary.
//
define([
"dojo/_base/declare",
"dijit/form/FilteringSelect"
],
function(declare, _FilteringSelect) {
return declare(
[_FilteringSelect], {
// minimum number of input characters to trigger search
minKeyCount: 2,
// the term for which we have queried the server for the last time
lastServerQueryTerm: null,
// The query URL which will be set on the store when a server query
// is needed
queryURL: null,
//------------------------------------------------------------------------
postCreate: function() {
this.inherited(arguments);
// Setting defaults
if (this.searchDelay == null)
this.searchDelay = 500;
if (this.searchAttr == null)
this.searchAttr = "label";
if (this.autoComplete == null)
this.autoComplete = true;
if (this.minKeyCount == null)
this.minKeyCount = 2;
},
escapeRegExp: function (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
replaceAll: function (find, replace, str) {
return str.replace(new RegExp(this.escapeRegExp(find), 'g'), replace);
},
startsWith: function (longStr, shortStr) {
return (longStr.match("^" + shortStr) == shortStr)
},
// override search method, count the input length
_startSearch: function (/*String*/ key) {
// If there is not enough text entered, we won't start querying
if (!key || key.length < this.minKeyCount) {
this.closeDropDown();
return;
}
// Deciding if the server needs to be queried
var serverQueryNeeded = false;
if (this.lastServerQueryTerm == null)
serverQueryNeeded = true;
else if (!this.startsWith(key, this.lastServerQueryTerm)) {
// the key does not start with the server queryterm
serverQueryNeeded = true;
}
if (serverQueryNeeded) {
// Creating a query url templated with the autocomplete term
var url = this.replaceAll('${autoCompleteTerm}', key, this.queryURL);
this.store.url = url
// We need to close the store in order to allow the FilteringSelect
// to re-open it with the new query term
this.store.close();
this.lastServerQueryTerm = key;
}
// Calling the super start search
this.inherited(arguments);
}
}
);
});
Notes:
I included some string functions to make it standalone, these should go to their proper places in your JS library.
The JavaScript embedded into the page which uses teh AutoComplete widget:
require([
"dojo/ready",
"dojo/data/ItemFileReadStore",
"gefc/dijit/AutoComplete",
"dojo/parser"
],
function(ready, ItemFileReadStore, AutoComplete) {
ready(function() {
// The initially displayed data (current value, possibly null)
// This makes it possible that the widget does not fire a query against
// the server immediately after initialization for getting a label for
// its current value
var dt = null;
<g:if test="${tenantInstance.technicalContact != null}">
dt = {identifier:"id", items:[
{id: "${tenantInstance.technicalContact.id}",
label:"${tenantInstance.technicalContact.name}"
}
]};
</g:if>
// If there is no current value, this will have no data
var partnerStore = new ItemFileReadStore(
{ data: dt,
urlPreventCache: true,
clearOnClose: true
}
);
var partnerSelect = new AutoComplete({
id: "technicalContactAC",
name: "technicalContact.id",
value: "${tenantInstance?.technicalContact?.id}",
displayValue: "${tenantInstance?.technicalContact?.name}",
queryURL: '<g:createLink controller="partner"
action="listForAutoComplete"
absolute="true"/>?term=\$\{autoCompleteTerm\}',
store: partnerStore,
searchAttr: "label",
autoComplete: true
},
"technicalContactAC"
);
})
})
Notes:
This is not standalone JavaScript, but generated with Grails on the server side, thus you see <g:if... and other server-side markup in the code). Replace those sections with your own markup.
<g:createLink will result in something like this after server-side page generation: /Limes/partner/listForAutoComplete?term=${autoCompleteTerm}
As of dojo 1.9, I would start by recommending that you replace your ItemFileReadStore by a store from the dojo/store package.
Then, I think dijit/form/FilteringSelect already has the features you need.
Given your requirement to avoid a server round-trip at the initial page startup, I would setup 2 different stores :
a dojo/store/Memory that would handle your initial data.
a dojo/store/JsonRest that queries your controller on subsequent requests.
Then, to avoid querying the server at each keystroke, set the FilteringSelect's intermediateChanges property to false, and implement your logic in the onChange extension point.
For the requirement of triggering the server call after a delay, implement that in the onChange as well. In the following example I did a simple setTimeout, but you should consider writing a better debounce method. See this blog post and the utility functions of dgrid.
I would do this in your GSP page :
require(["dojo/store/Memory", "dojo/store/JsonRest", "dijit/form/FilteringSelect", "dojo/_base/lang"],
function(Memory, JsonRest, FilteringSelect, lang) {
var initialPartnerStore = undefined;
<g:if test="${tenantInstance.technicalContact != null}">
dt = {identifier:"id", items:[
{id: "${tenantInstance.technicalContact.id}",
label:"${tenantInstance.technicalContact.name}"
}
]};
initialPartnerStore = new Memory({
data : dt
});
</g:if>
var partnerStore = new JsonRest({
target : '<g:createLink controller="partner" action="listForAutoComplete" absolute="true"/>',
});
var queryDelay = 500;
var select = new FilteringSelect({
id: "technicalContactAC",
name: "technicalContact.id",
value: "${tenantInstance?.technicalContact?.id}",
displayValue: "${tenantInstance?.technicalContact?.name}",
store: initialPartnerStore ? initialPartnerStore : partnerStore,
query : { term : ${autoCompleteTerm} },
searchAttr: "label",
autoComplete: true,
intermediateChanges : false,
onChange : function(newValue) {
// Change to the JsonRest store to query the server
if (this.store !== partnerStore) {
this.set("store", partnerStore);
}
// Only query after your desired delay
setTimeout(lang.hitch(this, function(){
this.set('query', { term : newValue }
}), queryDelay);
}
}).startup();
});
This code is untested, but you get the idea...

Knockout bindings are not working with jsTree

I'm trying to get jsTree (1.0-rc3) working with Knockout.js (2.2.1).
See example jsFiddle: http://jsfiddle.net/adeconsulting/qfr6A/
Note: I've included several JS resources in the Fiddle to match as close as possible my Visual Studio project, in case there's a conflict between libraries which might be causing this problem.
Run the Fiddle and navigate through the jsTree, it's a list of servers by their physical location and type. It helps to have Firebug's console open so you can see the ajax calls and responses. When you click a leaf node, an ajax call is made to retrieve the server details and display a form whose values use Knockout bindings. I hide the form when a non-leaf node is selected.
It works the first time you click a leaf node. After that, Knockout does not update the form for leaf node clicks. However, if you happen to click the Edit button, then all of a sudden the most recent server details ARE displayed.
I'm thinking that there's a conflict between jsTree and Knockout bindings, but don't know where to start troubleshooting what that might be.
Since stackoverflow apparently requires at least one code block, here's the JavaScript portion of the Fiddle:
// Global vars:
var prevJsTreeNodeId = null;
var serverModelBindingsApplied = false;
var serverLoadInProgress = false;
/*
* The knockout.js view model
*/
var ServerViewModel = function () {
// Data
var self = this;
self.IsReadOnly = ko.observable(true); // the form's input mode
self.btnEditSave = ko.observable("Edit"); // the Edit/Save button text
self.Server = ko.observable({}); // the Server object
// Operations
self.setEditable = function () {
self.IsReadOnly(false);
self.btnEditSave("Save");
};
self.setReadOnly = function () {
self.IsReadOnly(true);
self.btnEditSave("Edit");
};
self.doEditSave = function () {
var flag = self.IsReadOnly();
if (flag) {
// switch to Edit mode
self.setEditable();
}
else {
// switch back to readOnly
self.setReadOnly();
}
};
// use ajax to update the knockout.js view model's Server object for the specified server name
self.load = function (serverName) {
if (!serverLoadInProgress) {
serverLoadInProgress = true;
// use ajax to retrieve the server's details
var data = {
json: JSON.stringify({
ServerName: serverName,
PrimaryIP: "1.2.3.4",
BrandDesc: "Dell",
OSDesc: "Windows 2003 Server",
Location: "xyz"
}),
delay: 1
};
$.ajax({
url:"/echo/json/",
data:data,
type:"POST",
success:function(response)
{
console.log(response);
window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
// apply bindings the first time we retrieve a Server object
if (!serverModelBindingsApplied) {
ko.applyBindings(window.ServerViewModelInstance,
document.getElementById('servercontent'));
serverModelBindingsApplied = true;
}
else {
// hmmm... updating the view model's .Server property doesn't trigger the
// form to be updated, yet if we click the Edit button, the new values
// suddenly appear, so try emulating that here...
self.setReadOnly();
}
}
});
serverLoadInProgress = false;
}
};
}; // ServerViewModel
/*
* document load
*/
$(function () {
// configure the jsTree
$("#divtree")
.jstree({
"themes": { "theme": "default", "dots": true, "icons": true },
"plugins": ["themes", "html_data", "ui", "types"],
"types": {
"type_attr": "tag", // the attribute which contains the type name
"max_depth": -2, // disable depth check
"max_children": -2, // disable max children check
"valid_children": ["root"],
"types": {
"root": {
"valid_children": ["level1"]
},
"level1": {
"valid_children": ["level2"],
"start_drag": false,
"move_node": false,
"delete_node": false,
"remove": false
},
"level2": {
"valid_children": ["leaf"],
// use the theme icon for the level2 nodes
"start_drag": false,
"move_node": false,
"delete_node": false,
"remove": false
},
"leaf": {
"valid_children": "none"
}
}
}
});
// register to receive notifications from #divtree when a jsTree node is selected
$("#divtree").bind("select_node.jstree", function (event, data) {
// data.rslt.obj is the jquery extended node that was clicked
var key = data.rslt.obj.attr("key");
var id = data.rslt.obj.attr("id");
if (id == prevJsTreeNodeId) {
// user clicked the same node, nothing to do
return;
}
prevJsTreeNodeId = id;
// when a jsTree node is selected, reset the knockout.js view model to read only
window.ServerViewModelInstance.setReadOnly();
var idx = key.indexOf("Server");
if (idx === 0) { // "Server|servername"
// show the "servercontent" div
$("#servercontent").show();
// display the server details
var serverName = key.substr(idx + 7, key.length);
window.ServerViewModelInstance.load(serverName);
}
else {
// hide the "servercontent" div
$("#servercontent").hide();
}
});
// hide the "servercontent" div
$("#servercontent").hide();
// instantiate the knockout.js view model
window.ServerViewModelInstance = new ServerViewModel();
}); // document ready
// initialization timer routine to select the main jsTree node
setTimeout(function () {
// open the root node
$.jstree._reference("#divtree").open_node("#root");
}, 500);
Sorry for my bad formatting below - this editor is not my friend... :-/
If I understand you right, the detail panel for a clicked tree node isn't updated with the correct data - right?
Try to do the following:
change:
window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
to: window.ServerViewModelInstance.Server(response);
(e.g. not overwriting the initial ko.observable which you only binds once, instead updating its values)
and in view where you bind to the observables..
for instance instead of: ... "value: Server.ServerName, ...
change it to: ... "value: Server().ServerName, ...
(e.g executing the function before accessing the property)
It works and updates the form when clicking on a new server name node in the tree (tried in firefox)
A copy of your example with the modified code can be found at: http://jsfiddle.net/RZ92g/2/

How to make "jQuery UI tab" blink/ flash

I want to make "jQuery UI TAB" blink (like notification).
I have diffrent tabs (Inbox | Sent | Important). My timer function checks if there is a new message in inbox, if so, I want the Inbox tab to start blinking/ flashing unless its clicked open.
Have tried diffrent options like .effect(..), .tabs(fx: {..}) but nothing seems to work :(
Any idea if its possible or not?
Yes it's definitely possible.
To give me some practice, I've written a jQuery blinker plugin for you:
jQuery:
(function($){
// **********************************
// ***** Start: Private Members *****
var pluginName = 'blinker';
var blinkMain = function(data){
var that = this;
this.css(data.settings.css_1);
clearTimeout(data.timeout);
data.timeout = setTimeout(function(){
that.css(data.settings.css_0);
}, data.settings.cycle * data.settings.ratio);
};
// ***** Fin: Private Members *****
// ********************************
// *********************************
// ***** Start: Public Methods *****
var methods = {
init : function(options) {
//"this" is a jquery object on which this plugin has been invoked.
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
// If the plugin hasn't been initialized yet
if (!data){
var settings = {
css_0: {
color: $this.css('color'),
backgroundColor: $this.css('backgroundColor')
},
css_1: {
color: '#000',
backgroundColor: '#F90'
},
cycle: 2000,
ratio: 0.5
};
if(options) { $.extend(true, settings, options); }
$this.data(pluginName, {
target : $this,
settings: settings,
interval: null,
timeout: null,
blinking: false
});
}
});
},
start: function(){
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
if(!data.blinking){
blinkMain.call($this, data);
data.interval = setInterval(function(){
blinkMain.call($this, data);
}, data.settings.cycle);
data.blinking = true;
}
});
},
stop: function(){
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
clearInterval(data.interval);
clearTimeout(data.timeout);
data.blinking = false;
this.style = '';
});
}
};
// ***** Fin: Public Methods *****
// *******************************
// *****************************
// ***** Start: Supervisor *****
$.fn[pluginName] = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || !method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist in jQuery.' + pluginName );
}
};
// ***** Fin: Supervisor *****
// ***************************
})( jQuery );
See it in action here
The plugin and the fiddle are pretty raw in that I haven't tried to integrate with jQuery-ui-tabs. This may be easy or hard, I don't know, but providing each tab is addressable by class or id then it shouldn't be too difficult.
Something you may need to consider is stopping a blinking tab when it is clicked. For this you may wish to call the .blinker('stop') method directly (with a .on('click') handler) or from an appropriate jQuery-ui-tabs callback.
API
The plugin is properly written in jQuery's preferred pattern. It puts just one member in the jQuery.fn namespace and .blinker(...) will chain like standard jQuery methods.
Methods :
.blinker('init' [,options]) : Initialises selected element(s) with blinker behaviour. Called automatically with .blinker(options), or just .blinker() in its simplest form.
.blinker('start') : causes selected element(s) to start blinking between two styles as determined by plugin defaults and/or options.
.blinker('stop') : causes selected element(s) to stop blinking and return to their natural CSS style(s).
Options : a map of properties, which determine blinker styles and timing:
css_0 : (optional) a map of css properties representing the blink OFF-state.
css_1 : a map of CSS properties representing the blink ON-state.
cycle : the blink cycle time in milliseconds (default 2000).
ratio : ON time as a proportion of cycle time (default 0.5).
By omitting css_0 from the options map, the OFF state is determined by the element(s)' natural CSS styling defined elsewhere (typically in a stylesheet).
Default values are hard-coded for css_1.color, css_1.backgroundColor, cycle time and ratio. Changing the default settings programmatically is not handled, so for different default styling the plugin will need to be edited.
jQuery comes by default with a slew of effects to pick from. You can easily use them wherever you see the need for them and they can be applied like so:
$('#newmsg').effect("pulsate", {}, 1000);
Demo
yes... this is what you need...!!!
this is javascript
if(newmessage==true){
$('#chat-86de45de47-tab').effect("pulsate", {}, 1000);
}
i think it's

jqGrid dataUrl dropdown list not refreshing

I'm new to web development and working on my first ASP.NET MVC 3 app. I'm using jqGrid and noticed that refreshing the page does not refresh the values in the dropdownlist until I open the same page in another tab, then refreshing the first tab will pick up the changed values.
I've got a controller action that looks like this:
public JsonResult FavoriteToppings()
{
var all = GetFavoriteToppings();
return Json(all, JsonRequestBehavior.AllowGet);
}
and I've the part of the jqGrid definition looks like this:
{ name: 'ToppingID', index: 'ToppingID', width: 200,
editable: true, align: 'left', edittype: 'select', stype: 'select',
editoptions: {
dataUrl: '#Url.Action("FavoriteToppings", "Dessert")',
buildSelect: createSelectList
},
searchoptions: {
dataUrl: '#Url.Action("FavoriteToppings", "Dessert")',
buildSelect: createSelectList,
sopt: ['eq']
}
},
and createSelectList looks like this:
createSelectList = function (data) {
var response, s = '<select>', i, l, ri;
if (typeof (data) === "string") {
//var leng = data.length - 1;
response = jQuery.parseJSON(data);
}
else {
response = jQuery.parseJSON(data.responseText);
s += '<option value="">Select...</option>';
}
if (response && response.length) {
for (i = 0, l = response.length; i < l; i += 1) {
ri = response[i];
s += '<option value="' + ri + '">' + ri + '</option>';
}
}
return s + '</select>';
}
I noticed this when editing one of the topping names. I changed the misspelled "Hot Fugde" to "Hot Fudge" and saved that off. The underlying data in the table gets updated to show the correctly spelled topping (i.e., all the rows correctly reflect the change) when I refresh the page but the filter dropdown doesn't. That action isn't called at all after the first time to pick up the change.
When I do open the same page in a different page of the browser, then the action gets called. After that, refreshing the first tab will result in the correctly spelled entry showing up in the select list.
Perhaps I'm just going about this incorrectly. Any guidance?
I think you have to use
ajaxSelectOptions: { cache: false }
jqGrid parameter to set additional parameter cache: false for the jQuery.ajax used by jqGrid if it get the data from the server from the dataUrl.
I've noticed that cache policies vary from browser to browser (chrome seems to have the most aggressive caching policy). Does the behavior repeat in all browsers? Ctrl-F5 work?

Resources