2 * (c) 2005-2009 Richard Cowin (http://openrico.org)
3 * (c) 2005-2009 Matt Brown (http://dowdybrown.com)
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6 * file except in compliance with the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software distributed under the
11 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
12 * either express or implied. See the License for the specific language governing permissions
13 * and limitations under the License.
16 if(typeof Rico=='undefined') throw("LiveGridAjax requires the Rico JavaScript framework");
18 if (!Rico.Buffer) Rico.Buffer = {};
20 Rico.Buffer.AjaxXML = function(url,options,ajaxOptions) {
21 this.initialize(url,options,ajaxOptions);
24 Rico.Buffer.AjaxXML.prototype = {
26 * @class Implements buffer for LiveGrid. Loads data from server via a single AJAX call.
27 * @extends Rico.Buffer.Base
30 initialize: function(url,options,ajaxOptions) {
31 Rico.extend(this, new Rico.Buffer.Base());
32 Rico.extend(this, Rico.Buffer.AjaxXMLMethods);
34 this.options.bufferTimeout=20000; // time to wait for ajax response (milliseconds)
35 this.options.requestParameters=[];
36 this.options.waitMsg=Rico.getPhraseById("waitForData"); // replace this with an image tag if you prefer
37 this.options.canFilter=true;
38 this.options.fmt='xml';
39 Rico.extend(this.options, options || {});
40 this.ajaxOptions = { parameters: null, method : 'get' };
41 Rico.extend(this.ajaxOptions, ajaxOptions || {});
43 this.processingRequest=false;
44 this.pendingRequest=-2;
50 Rico.Buffer.AjaxXMLMethods = {
52 /** @lends Rico.Buffer.AjaxXML# */
53 fetch: function(offset) {
55 this.foundRowCount=true;
57 this.processingRequest=true;
58 this.liveGrid.showMsg(this.options.waitMsg);
59 this.timeoutHandler = Rico.runLater(this.options.bufferTimeout,this,'handleTimedOut');
60 this.ajaxOptions.parameters = this.formQueryHashXML(0,-1);
61 Rico.log('sending request');
63 if (typeof this.dataSource=='string') {
64 this.ajaxOptions.onComplete = function(xhr) { self.ajaxUpdate(offset,xhr); };
65 new Rico.ajaxRequest(this.dataSource, this.ajaxOptions);
67 this.ajaxOptions.onComplete = function(newRows, newStyle, totalRows, errMsg) { self.jsUpdate(offset, newRows, newStyle, totalRows, errMsg); };
68 this.dataSource(this.ajaxOptions);
73 this.setTotalRows(this.size);
76 this.liveGrid.refreshContents(offset);
81 * Server did not respond in time... assume that there could have been
82 * an error, and allow requests to be processed again.
84 handleTimedOut: function() {
85 Rico.log("Request Timed Out");
86 this.liveGrid.showMsg(Rico.getPhraseById("requestTimedOut"));
89 formQueryHashXML: function(startPos,fetchSize) {
91 id: this.liveGrid.tableId,
92 page_size: (typeof fetchSize=='number') ? fetchSize : this.totalRows,
93 offset: startPos.toString()
95 if (!this.foundRowCount) queryHash['get_total']='true';
96 if (this.options.requestParameters) {
97 for ( var i=0; i < this.options.requestParameters.length; i++ ) {
98 var anArg = this.options.requestParameters[i];
99 if ( anArg.name != undefined && anArg.value != undefined ) {
100 queryHash[anArg.name]=anArg.value;
102 var ePos = anArg.indexOf('=');
103 var argName = anArg.substring( 0, ePos );
104 var argValue = anArg.substring( ePos + 1 );
105 queryHash[argName]=argValue;
112 clearTimer: function() {
113 if(typeof this.timeoutHandler != "number") return;
114 window.clearTimeout(this.timeoutHandler);
115 delete this.timeoutHandler;
118 // used by both XML and SQL buffers
119 jsUpdate: function(startPos, newRows, newStyle, totalRows, errMsg) {
121 this.processingRequest=false;
122 Rico.log("jsUpdate: "+arguments.length);
124 Rico.log("jsUpdate: received error="+errMsg);
125 this.liveGrid.showMsg(Rico.getPhraseById("requestError",errMsg));
128 this.rcvdRows = newRows.length;
129 if (typeof totalRows=='number') {
130 this.rowcntContent = totalRows.toString();
131 this.rcvdRowCount = true;
132 this.foundRowCount = true;
133 Rico.log("jsUpdate: found RowCount="+this.rowcntContent);
135 this.updateBuffer(startPos, newRows, newStyle);
136 if (this.options.onAjaxUpdate)
137 this.options.onAjaxUpdate();
138 this.updateGrid(startPos);
139 if (this.options.TimeOut && this.timerMsg)
140 this.restartSessionTimer();
141 if (this.pendingRequest>=-1) {
142 var offset=this.pendingRequest;
143 Rico.log("jsUpdate: found pending request for offset="+offset);
144 this.pendingRequest=-2;
149 // used by both XML and SQL buffers
150 ajaxUpdate: function(startPos,xhr) {
152 this.processingRequest=false;
153 if (xhr.status != 200) {
154 Rico.log("ajaxUpdate: received http error="+xhr.status);
155 this.liveGrid.showMsg(Rico.getPhraseById("httpError",xhr.status));
158 this._responseHandler=this['processResponse'+this.options.fmt.toUpperCase()];
159 if (!this._responseHandler(startPos,xhr)) return;
160 if (this.options.onAjaxUpdate)
161 this.options.onAjaxUpdate();
162 this.updateGrid(startPos);
163 if (this.options.TimeOut && this.timerMsg)
164 this.restartSessionTimer();
165 if (this.pendingRequest>=-1) {
166 var offset=this.pendingRequest;
167 Rico.log("ajaxUpdate: found pending request for offset="+offset);
168 this.pendingRequest=-2;
173 // used by both XML and SQL buffers
174 processResponseXML: function(startPos,request) {
175 // The response text may contain META DATA for debugging if client side debugging is enabled in VS
\r
176 var xmlDoc = request.responseXML;
\r
177 if (request.responseText.substring(0, 4) == "<!--") {
\r
178 var nEnd = request.responseText.indexOf("-->");
\r
180 this.liveGrid.showMsg('Web server error - client side debugging may be enabled');
\r
183 xmlDoc = Rico.createXmlDocument();
\r
184 xmlDoc.loadXML(request.responseText.substring(nEnd+3));
\r
188 alert("Data provider returned an invalid XML response");
189 Rico.log("Data provider returned an invalid XML response");
193 // process children of <ajax-response>
194 var response = xmlDoc.getElementsByTagName("ajax-response");
195 if (response == null || response.length != 1) {
196 alert("Received invalid response from server");
199 Rico.log("Processing ajax-response");
201 this.rcvdRowCount = false;
202 var ajaxResponse=response[0];
203 var debugtags = ajaxResponse.getElementsByTagName('debug');
204 for (var i=0; i<debugtags.length; i++)
205 Rico.log("ajaxUpdate: debug msg "+i+": "+Rico.getContentAsString(debugtags[i],this.options.isEncoded));
206 var error = ajaxResponse.getElementsByTagName('error');
207 if (error.length > 0) {
208 var msg=Rico.getContentAsString(error[0],this.options.isEncoded);
209 alert("Data provider returned an error:\n"+msg);
210 Rico.log("Data provider returned an error:\n"+msg);
213 var rowsElement = ajaxResponse.getElementsByTagName('rows')[0];
215 Rico.log("ajaxUpdate: invalid response");
216 this.liveGrid.showMsg(Rico.getPhraseById("invalidResponse"));
219 var rowcnttags = ajaxResponse.getElementsByTagName('rowcount');
220 if (rowcnttags && rowcnttags.length==1) {
221 this.rowcntContent = Rico.getContentAsString(rowcnttags[0],this.options.isEncoded);
222 this.rcvdRowCount = true;
223 this.foundRowCount = true;
224 Rico.log("ajaxUpdate: found RowCount="+this.rowcntContent);
228 this.updateUI = rowsElement.getAttribute("update_ui") == "true";
229 this.rcvdOffset = rowsElement.getAttribute("offset");
230 Rico.log("ajaxUpdate: rcvdOffset="+this.rcvdOffset);
231 var newRows = this.dom2jstable(rowsElement);
232 var newStyle = (this.options.acceptStyle) ? this.dom2jstableStyle(rowsElement) : false;
233 this.rcvdRows = newRows.length;
234 this.updateBuffer(startPos, newRows, newStyle);
238 dom2jstableStyle: function(rowsElement,firstRow) {
239 var acceptStyle=this.options.acceptStyle;
240 Rico.log("dom2jstableStyle start");
242 var trs = rowsElement.getElementsByTagName("tr");
243 for ( var i=firstRow || 0; i < trs.length; i++ ) {
245 var cells = trs[i].getElementsByTagName("td");
246 for ( var j=0; j < cells.length ; j++ ) {
247 row[j]=cells[j].getAttribute('style') || '';
251 Rico.log("dom2jstableStyle end");
255 processResponseJSON: function(startPos,request) {
256 var json = Rico.getJSON(request);
257 if (!json || json == null) {
258 alert("Data provider returned an invalid JSON response");
259 Rico.log("Data provider returned an invalid JSON response");
264 for (var i=0; i<json.debug.length; i++)
265 Rico.writeDebugMsg("debug msg "+i+": "+json.debug[i]);
268 alert("Data provider returned an error:\n"+json.error);
269 Rico.writeDebugMsg("Data provider returned an error:\n"+json.error);
274 this.rowcntContent = json.rowcount;
275 this.rcvdRowCount = true;
276 this.foundRowCount = true;
277 Rico.writeDebugMsg("loadRows, found RowCount="+json.rowcount);
280 this.rcvdRows = json.rows.length;
281 this.updateBuffer(startPos, json.rows, json.styles);
285 // specific to XML buffer
286 updateBuffer: function(start, newRows, newStyle) {
287 this.baseRows = newRows;
288 this.attr = newStyle;
289 Rico.log("updateBuffer: # of rows="+this.rcvdRows);
290 this.rcvdRowCount=true;
291 this.rowcntContent=this.rcvdRows;
292 if (typeof this.delayedSortCol=='number')
293 this.sortBuffer(this.delayedSortCol);
298 // used by both XML and SQL buffers
299 updateGrid: function(offset) {
300 Rico.log("updateGrid, size="+this.size+' rcv cnt type='+typeof(this.rowcntContent));
302 if (this.rcvdRowCount==true) {
303 Rico.log("found row cnt: "+this.rowcntContent);
304 var eofrow=parseInt(this.rowcntContent,10);
305 var lastTotalRows=this.totalRows;
306 if (!isNaN(eofrow) && eofrow!=lastTotalRows) {
307 this.setTotalRows(eofrow);
308 newpos=Math.min(this.liveGrid.topOfLastPage(),offset);
309 Rico.log("updateGrid: new rowcnt="+eofrow+" newpos="+newpos);
310 if (lastTotalRows==0 && this.liveGrid.sizeTo=='data')
311 Rico.runLater(100,this.liveGrid,'adjustPageSize'); // FF takes a long time to calc initial size
312 this.liveGrid.scrollToRow(newpos);
313 if ( this.isInRange(newpos) ) {
314 this.liveGrid.refreshContents(newpos);
321 var lastbufrow=offset+this.rcvdRows;
322 if (lastbufrow>this.totalRows) {
323 var newcnt=lastbufrow;
324 Rico.log("extending totrows to "+newcnt);
325 this.setTotalRows(newcnt);
328 newpos=this.liveGrid.pixeltorow(this.liveGrid.scrollDiv.scrollTop);
329 Rico.log("updateGrid: newpos="+newpos);
330 this.liveGrid.refreshContents(newpos);
337 Rico.Buffer.AjaxSQL = function(url,options,ajaxOptions) {
338 this.initialize(url,options,ajaxOptions);
341 Rico.Buffer.AjaxSQL.prototype = {
343 * @class Implements buffer for LiveGrid. Loads data from server in chunks as user scrolls through the grid.
344 * @extends Rico.Buffer.AjaxXML
347 initialize: function(url,options,ajaxOptions) {
348 Rico.extend(this, new Rico.Buffer.AjaxXML());
349 Rico.extend(this, Rico.Buffer.AjaxSQLMethods);
351 this.options.canFilter=true;
352 this.options.largeBufferSize = 7.0; // 7 pages
353 this.options.nearLimitFactor = 1.0; // 1 page
354 Rico.extend(this.options, options || {});
355 Rico.extend(this.ajaxOptions, ajaxOptions || {});
359 Rico.Buffer.AjaxSQLMethods = {
360 /** @lends Rico.Buffer.AjaxSQL# */
362 registerGrid: function(liveGrid) {
363 this.liveGrid = liveGrid;
364 this.sessionExpired=false;
365 this.timerMsg=document.getElementById(liveGrid.tableId+'_timer');
366 if (this.options.TimeOut && this.timerMsg) {
367 if (!this.timerMsg.title) this.timerMsg.title=Rico.getPhraseById("sessionExpireMinutes");
368 this.restartSessionTimer();
372 setBufferSize: function(pageSize) {
373 this.maxFetchSize = Math.max(50,parseInt(this.options.largeBufferSize * pageSize,10));
374 this.nearLimit = parseInt(this.options.nearLimitFactor * pageSize,10);
375 this.maxBufferSize = this.maxFetchSize * 3;
378 restartSessionTimer: function() {
379 if (this.sessionExpired==true) return;
380 this.sessionEndTime = (new Date()).getTime() + this.options.TimeOut*60000;
381 if (this.sessionTimer) clearTimeout(this.sessionTimer);
382 this.updateSessionTimer();
385 updateSessionTimer: function() {
386 var now=(new Date()).getTime();
387 if (now > this.sessionEndTime) {
388 this.displaySessionTimer(Rico.getPhraseById("sessionExpired"));
389 this.timerMsg.style.backgroundColor="red";
390 this.sessionExpired=true;
392 var timeRemaining=Math.ceil((this.sessionEndTime - now) / 60000);
393 this.displaySessionTimer(timeRemaining);
394 this.sessionTimer=Rico.runLater(10000,this,'updateSessionTimer');
398 displaySessionTimer: function(msg) {
399 this.timerMsg.innerHTML=' '+msg+' ';
403 * Update the grid with fresh data from the database, maintaining scroll position.
404 * @param resetRowCount indicates whether the total row count should be refreshed as well
406 refresh: function(resetRowCount) {
407 var lastGridPos=this.liveGrid.lastRowPos;
\r
410 this.setTotalRows(0);
411 this.foundRowCount = false;
413 this.liveGrid.clearBookmark();
414 this.liveGrid.clearRows();
415 this.fetch(lastGridPos);
419 * Fetch data from database.
420 * @param offset position (row) within the dataset (-1=clear existing buffer before issuing request)
422 fetch: function(offset) {
423 Rico.log("AjaxSQL fetch: offset="+offset+', lastOffset='+this.lastOffset);
424 if (this.processingRequest) {
425 Rico.log("AjaxSQL fetch: queue request");
426 this.pendingRequest=offset;
429 if ((typeof offset == 'undefined') || (offset < 0)) {
431 this.setTotalRows(0);
432 this.foundRowCount = false;
435 var lastOffset = this.lastOffset;
436 this.lastOffset = offset;
437 if (this.isInRange(offset)) {
438 Rico.log("AjaxSQL fetch: in buffer");
439 this.liveGrid.refreshContents(offset);
440 if (offset > lastOffset) {
441 if (offset+this.liveGrid.pageSize < this.endPos()-this.nearLimit) return;
442 if (this.endPos()==this.totalRows && this.foundRowCount) return;
443 } else if (offset < lastOffset) {
444 if (offset > this.startPos+this.nearLimit) return;
445 if (this.startPos==0) return;
448 if (offset >= this.totalRows && this.foundRowCount) return;
450 this.processingRequest=true;
451 Rico.log("AjaxSQL fetch: processing offset="+offset);
452 var bufferStartPos = this.getFetchOffset(offset);
453 var fetchSize = this.getFetchSize(bufferStartPos);
454 var partialLoaded = false;
456 this.liveGrid.showMsg(this.options.waitMsg);
457 this.timeoutHandler = Rico.runLater(this.options.bufferTimeout, this, 'handleTimedOut');
458 this.ajaxOptions.parameters = this.formQueryHashSQL(bufferStartPos,fetchSize,this.options.fmt);
460 Rico.log('sending req #'+this.requestCount);
462 if (typeof this.dataSource=='string') {
463 this.ajaxOptions.onComplete = function(xhr) { self.ajaxUpdate(bufferStartPos, xhr); };
464 new Rico.ajaxRequest(this.dataSource, this.ajaxOptions);
466 this.ajaxOptions.onComplete = function(newRows, newStyle, totalRows, errMsg) { self.jsUpdate(bufferStartPos, newRows, newStyle, totalRows, errMsg); };
467 this.dataSource(this.ajaxOptions);
471 formQueryHashSQL: function(startPos,fetchSize,fmt) {
472 var queryHash=this.formQueryHashXML(startPos,fetchSize);
473 queryHash[this.liveGrid.actionId]="query";
474 if (fmt) queryHash._fmt=fmt;
477 Rico.extend(queryHash,this.sortParm);
480 for (var n=0; n<this.liveGrid.columns.length; n++) {
481 var c=this.liveGrid.columns[n];
482 if (c.filterType == Rico.ColumnConst.UNFILTERED) continue;
483 var colnum=typeof(c.format.filterCol)=='number' ? c.format.filterCol : c.index;
484 queryHash['f['+colnum+'][op]']=c.filterOp;
485 queryHash['f['+colnum+'][len]']=c.filterValues.length;
486 for (var i=0; i<c.filterValues.length; i++) {
487 var fval=c.filterValues[i];
488 if (c.filterOp=='LIKE' && fval.indexOf('*')==-1) fval='*'+fval+'*';
489 queryHash['f['+colnum+']['+i+']']=fval;
495 getFetchSize: function(adjustedOffset) {
496 var adjustedSize = 0;
497 if (adjustedOffset >= this.startPos) { //appending
498 var endFetchOffset = this.maxFetchSize + adjustedOffset;
499 adjustedSize = endFetchOffset - adjustedOffset;
500 if(adjustedOffset == 0 && adjustedSize < this.maxFetchSize)
501 adjustedSize = this.maxFetchSize;
502 Rico.log("getFetchSize/append, adjustedSize="+adjustedSize+" adjustedOffset="+adjustedOffset+' endFetchOffset='+endFetchOffset);
503 } else { //prepending
504 adjustedSize = Math.min(this.startPos - adjustedOffset,this.maxFetchSize);
509 getFetchOffset: function(offset) {
510 var adjustedOffset = offset;
511 if (offset > this.startPos)
512 adjustedOffset = Math.max(offset, this.endPos()); //appending
513 else if (offset + this.maxFetchSize >= this.startPos)
514 adjustedOffset = Math.max(this.startPos - this.maxFetchSize, 0); //prepending
515 return adjustedOffset;
518 updateBuffer: function(start, newRows, newStyle) {
519 Rico.log("updateBuffer: start="+start+", # of rows="+this.rcvdRows);
520 if (this.rows.length == 0) { // initial load
522 this.attr = newStyle;
523 this.startPos = start;
524 } else if (start > this.startPos) { //appending
525 if (this.startPos + this.rows.length < start) {
527 this.attr = newStyle;
528 this.startPos = start;
530 this.rows = this.rows.concat( newRows.slice(0, newRows.length));
531 if (this.attr) this.attr = this.attr.concat( newStyle.slice(0, newStyle.length));
532 if (this.rows.length > this.maxBufferSize) {
533 var fullSize = this.rows.length;
534 this.rows = this.rows.slice(this.rows.length - this.maxBufferSize, this.rows.length);
535 if (this.attr) this.attr = this.attr.slice(this.attr.length - this.maxBufferSize, this.attr.length);
536 this.startPos = this.startPos + (fullSize - this.rows.length);
539 } else { //prepending
540 if (start + newRows.length < this.startPos) {
542 this.attr = newStyle;
544 this.rows = newRows.slice(0, this.startPos).concat(this.rows);
545 if (newStyle) this.attr = newStyle.slice(0, this.startPos).concat(this.attr);
546 if (this.maxBufferSize && this.rows.length > this.maxBufferSize) {
547 this.rows = this.rows.slice(0, this.maxBufferSize);
548 if (this.attr) this.attr = this.attr.slice(0, this.maxBufferSize);
551 this.startPos = start;
553 this.size = this.rows.length;
556 sortBuffer: function(colnum) {
558 var col=this.liveGrid.columns[colnum];
559 if (this.options.sortParmFmt) {
560 this.sortParm['sort_col']=col[this.options.sortParmFmt];
561 this.sortParm['sort_dir']=col.getSortDirection();
563 this.sortParm['s'+colnum]=col.getSortDirection();
568 printAllSQL: function(exportType) {
569 var parms=this.formQueryHashSQL(0,this.liveGrid.options.maxPrint,exportType);
570 parms.hidden=this.liveGrid.listInvisible('index').join(',');
571 var url=this.dataSource+'?'+Rico.toQueryString(parms);
572 window.open(url,'',this.liveGrid.options.exportWindow);
575 printVisibleSQL: function(exportType) {
576 var parms=this.formQueryHashSQL(this.liveGrid.contentStartPos-1, this.liveGrid.pageSize, exportType);
577 parms.hidden=this.liveGrid.listInvisible('index').join(',');
578 var url=this.dataSource+'?'+Rico.toQueryString(parms);
579 window.open(url,'',this.liveGrid.options.exportWindow);
582 // for datasource that is a javascript function
583 _printAll: function() {
584 this.liveGrid.exportStart();
585 this.ajaxOptions.parameters = this.formQueryHashSQL(0,this.liveGrid.options.maxPrint);
587 this.ajaxOptions.onComplete = function() { self._jsExport(); };
588 this.dataSource(this.ajaxOptions);
591 _jsExport: function(newRows, newStyle, totalRows, errMsg) {
592 Rico.log("_jsExport: "+arguments.length);
594 Rico.log("_jsExport: received error="+errMsg);
595 this.liveGrid.showMsg(Rico.getPhraseById("requestError",errMsg));
598 this.exportBuffer(newRows,0);
599 this.liveGrid.exportFinish();