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, newAttr, totalRows, errMsg) { self.jsUpdate(offset, newRows, newAttr, 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, newAttr, 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, newAttr);
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) return false;
197 this.rcvdRowCount = false;
198 var ajaxResponse=response[0];
199 var debugtags = ajaxResponse.getElementsByTagName('debug');
200 for (var i=0; i<debugtags.length; i++)
201 Rico.log("ajaxUpdate: debug msg "+i+": "+Rico.getContentAsString(debugtags[i],this.options.isEncoded));
202 var error = ajaxResponse.getElementsByTagName('error');
203 if (error.length > 0) {
204 var msg=Rico.getContentAsString(error[0],this.options.isEncoded);
205 alert("Data provider returned an error:\n"+msg);
206 Rico.log("Data provider returned an error:\n"+msg);
209 var rowsElement = ajaxResponse.getElementsByTagName('rows')[0];
211 Rico.log("ajaxUpdate: invalid response");
212 this.liveGrid.showMsg(Rico.getPhraseById("invalidResponse"));
215 var rowcnttags = ajaxResponse.getElementsByTagName('rowcount');
216 if (rowcnttags && rowcnttags.length==1) {
217 this.rowcntContent = Rico.getContentAsString(rowcnttags[0],this.options.isEncoded);
218 this.rcvdRowCount = true;
219 this.foundRowCount = true;
220 Rico.log("ajaxUpdate: found RowCount="+this.rowcntContent);
224 this.updateUI = rowsElement.getAttribute("update_ui") == "true";
225 this.rcvdOffset = rowsElement.getAttribute("offset");
226 Rico.log("ajaxUpdate: rcvdOffset="+this.rcvdOffset);
227 var newRows = this.dom2jstable(rowsElement);
228 var newAttr = (this.options.acceptAttr.length > 0) ? this.dom2jstableAttr(rowsElement) : false;
229 this.rcvdRows = newRows.length;
230 this.updateBuffer(startPos, newRows, newAttr);
234 processResponseJSON: function(startPos,request) {
235 var json = Rico.getJSON(request);
236 if (!json || json == null) {
237 alert("Data provider returned an invalid JSON response");
238 Rico.log("Data provider returned an invalid JSON response");
243 for (var i=0; i<json.debug.length; i++)
244 Rico.writeDebugMsg("debug msg "+i+": "+json.debug[i]);
247 alert("Data provider returned an error:\n"+json.error);
248 Rico.writeDebugMsg("Data provider returned an error:\n"+json.error);
253 this.rowcntContent = json.rowcount;
254 this.rcvdRowCount = true;
255 this.foundRowCount = true;
256 Rico.writeDebugMsg("loadRows, found RowCount="+json.rowcount);
259 this.rcvdRows = json.rows.length;
260 this.updateBuffer(startPos, json.rows);
264 // specific to XML buffer
265 updateBuffer: function(start, newRows, newAttr) {
266 this.baseRows = newRows;
268 Rico.log("updateBuffer: # of rows="+this.rcvdRows);
269 this.rcvdRowCount=true;
270 this.rowcntContent=this.rcvdRows;
271 if (typeof this.delayedSortCol=='number')
272 this.sortBuffer(this.delayedSortCol);
277 // used by both XML and SQL buffers
278 updateGrid: function(offset) {
279 Rico.log("updateGrid, size="+this.size+' rcv cnt type='+typeof(this.rowcntContent));
281 if (this.rcvdRowCount==true) {
282 Rico.log("found row cnt: "+this.rowcntContent);
283 var eofrow=parseInt(this.rowcntContent,10);
284 var lastTotalRows=this.totalRows;
285 if (!isNaN(eofrow) && eofrow!=lastTotalRows) {
286 this.setTotalRows(eofrow);
287 newpos=Math.min(this.liveGrid.topOfLastPage(),offset);
288 Rico.log("updateGrid: new rowcnt="+eofrow+" newpos="+newpos);
289 if (lastTotalRows==0 && this.liveGrid.sizeTo=='data')
290 Rico.runLater(100,this.liveGrid,'adjustPageSize'); // FF takes a long time to calc initial size
291 this.liveGrid.scrollToRow(newpos);
292 if ( this.isInRange(newpos) ) {
293 this.liveGrid.refreshContents(newpos);
300 var lastbufrow=offset+this.rcvdRows;
301 if (lastbufrow>this.totalRows) {
302 var newcnt=lastbufrow;
303 Rico.log("extending totrows to "+newcnt);
304 this.setTotalRows(newcnt);
307 newpos=this.liveGrid.pixeltorow(this.liveGrid.scrollDiv.scrollTop);
308 Rico.log("updateGrid: newpos="+newpos);
309 this.liveGrid.refreshContents(newpos);
316 Rico.Buffer.AjaxSQL = function(url,options,ajaxOptions) {
317 this.initialize(url,options,ajaxOptions);
320 Rico.Buffer.AjaxSQL.prototype = {
322 * @class Implements buffer for LiveGrid. Loads data from server in chunks as user scrolls through the grid.
323 * @extends Rico.Buffer.AjaxXML
326 initialize: function(url,options,ajaxOptions) {
327 Rico.extend(this, new Rico.Buffer.AjaxXML());
328 Rico.extend(this, Rico.Buffer.AjaxSQLMethods);
330 this.options.canFilter=true;
331 this.options.largeBufferSize = 7.0; // 7 pages
332 this.options.nearLimitFactor = 1.0; // 1 page
333 Rico.extend(this.options, options || {});
334 Rico.extend(this.ajaxOptions, ajaxOptions || {});
338 Rico.Buffer.AjaxSQLMethods = {
339 /** @lends Rico.Buffer.AjaxSQL# */
341 registerGrid: function(liveGrid) {
342 this.liveGrid = liveGrid;
343 this.sessionExpired=false;
344 this.timerMsg=document.getElementById(liveGrid.tableId+'_timer');
345 if (this.options.TimeOut && this.timerMsg) {
346 if (!this.timerMsg.title) this.timerMsg.title=Rico.getPhraseById("sessionExpireMinutes");
347 this.restartSessionTimer();
351 setBufferSize: function(pageSize) {
352 this.maxFetchSize = Math.max(50,parseInt(this.options.largeBufferSize * pageSize,10));
353 this.nearLimit = parseInt(this.options.nearLimitFactor * pageSize,10);
354 this.maxBufferSize = this.maxFetchSize * 3;
357 restartSessionTimer: function() {
358 if (this.sessionExpired==true) return;
359 this.sessionEndTime = (new Date()).getTime() + this.options.TimeOut*60000;
360 if (this.sessionTimer) clearTimeout(this.sessionTimer);
361 this.updateSessionTimer();
364 updateSessionTimer: function() {
365 var now=(new Date()).getTime();
366 if (now > this.sessionEndTime) {
367 this.displaySessionTimer(Rico.getPhraseById("sessionExpired"));
368 this.timerMsg.style.backgroundColor="red";
369 this.sessionExpired=true;
371 var timeRemaining=Math.ceil((this.sessionEndTime - now) / 60000);
372 this.displaySessionTimer(timeRemaining);
373 this.sessionTimer=Rico.runLater(10000,this,'updateSessionTimer');
377 displaySessionTimer: function(msg) {
378 this.timerMsg.innerHTML=' '+msg+' ';
382 * Update the grid with fresh data from the database, maintaining scroll position.
383 * @param resetRowCount indicates whether the total row count should be refreshed as well
385 refresh: function(resetRowCount) {
386 var lastGridPos=this.liveGrid.lastRowPos;
\r
389 this.setTotalRows(0);
390 this.foundRowCount = false;
392 this.liveGrid.clearBookmark();
393 this.liveGrid.clearRows();
394 this.fetch(lastGridPos);
398 * Fetch data from database.
399 * @param offset position (row) within the dataset (-1=clear existing buffer before issuing request)
401 fetch: function(offset) {
402 Rico.log("AjaxSQL fetch: offset="+offset+', lastOffset='+this.lastOffset);
403 if (this.processingRequest) {
404 Rico.log("AjaxSQL fetch: queue request");
405 this.pendingRequest=offset;
410 this.setTotalRows(0);
411 this.foundRowCount = false;
414 var lastOffset = this.lastOffset;
415 this.lastOffset = offset;
416 if (this.isInRange(offset)) {
417 Rico.log("AjaxSQL fetch: in buffer");
418 this.liveGrid.refreshContents(offset);
419 if (offset > lastOffset) {
420 if (offset+this.liveGrid.pageSize < this.endPos()-this.nearLimit) return;
421 if (this.endPos()==this.totalRows && this.foundRowCount) return;
422 } else if (offset < lastOffset) {
423 if (offset > this.startPos+this.nearLimit) return;
424 if (this.startPos==0) return;
427 if (offset >= this.totalRows && this.foundRowCount) return;
429 this.processingRequest=true;
430 Rico.log("AjaxSQL fetch: processing offset="+offset);
431 var bufferStartPos = this.getFetchOffset(offset);
432 var fetchSize = this.getFetchSize(bufferStartPos);
433 var partialLoaded = false;
435 this.liveGrid.showMsg(this.options.waitMsg);
436 this.timeoutHandler = Rico.runLater(this.options.bufferTimeout, this, 'handleTimedOut');
437 this.ajaxOptions.parameters = this.formQueryHashSQL(bufferStartPos,fetchSize,this.options.fmt);
439 Rico.log('sending req #'+this.requestCount);
441 if (typeof this.dataSource=='string') {
442 this.ajaxOptions.onComplete = function(xhr) { self.ajaxUpdate(bufferStartPos, xhr); };
443 new Rico.ajaxRequest(this.dataSource, this.ajaxOptions);
445 this.ajaxOptions.onComplete = function(newRows, newAttr, totalRows, errMsg) { self.jsUpdate(bufferStartPos, newRows, newAttr, totalRows, errMsg); };
446 this.dataSource(this.ajaxOptions);
450 formQueryHashSQL: function(startPos,fetchSize,fmt) {
451 var queryHash=this.formQueryHashXML(startPos,fetchSize);
452 queryHash[this.liveGrid.actionId]="query";
453 if (fmt) queryHash._fmt=fmt;
456 Rico.extend(queryHash,this.sortParm);
459 for (var n=0; n<this.liveGrid.columns.length; n++) {
460 var c=this.liveGrid.columns[n];
461 if (c.filterType == Rico.ColumnConst.UNFILTERED) continue;
462 var colnum=typeof(c.format.filterCol)=='number' ? c.format.filterCol : c.index;
463 queryHash['f['+colnum+'][op]']=c.filterOp;
464 queryHash['f['+colnum+'][len]']=c.filterValues.length;
465 for (var i=0; i<c.filterValues.length; i++) {
466 var fval=c.filterValues[i];
467 if (c.filterOp=='LIKE' && fval.indexOf('*')==-1) fval='*'+fval+'*';
468 queryHash['f['+colnum+']['+i+']']=fval;
474 getFetchSize: function(adjustedOffset) {
475 var adjustedSize = 0;
476 if (adjustedOffset >= this.startPos) { //appending
477 var endFetchOffset = this.maxFetchSize + adjustedOffset;
478 adjustedSize = endFetchOffset - adjustedOffset;
479 if(adjustedOffset == 0 && adjustedSize < this.maxFetchSize)
480 adjustedSize = this.maxFetchSize;
481 Rico.log("getFetchSize/append, adjustedSize="+adjustedSize+" adjustedOffset="+adjustedOffset+' endFetchOffset='+endFetchOffset);
482 } else { //prepending
483 adjustedSize = Math.min(this.startPos - adjustedOffset,this.maxFetchSize);
488 getFetchOffset: function(offset) {
489 var adjustedOffset = offset;
490 if (offset > this.startPos)
491 adjustedOffset = Math.max(offset, this.endPos()); //appending
492 else if (offset + this.maxFetchSize >= this.startPos)
493 adjustedOffset = Math.max(this.startPos - this.maxFetchSize, 0); //prepending
494 return adjustedOffset;
497 updateBuffer: function(start, newRows, newAttr) {
498 Rico.log("updateBuffer: start="+start+", # of rows="+this.rcvdRows);
499 if (this.rows.length == 0) { // initial load
502 this.startPos = start;
503 } else if (start > this.startPos) { //appending
504 if (this.startPos + this.rows.length < start) {
507 this.startPos = start;
509 this.rows = this.rows.concat( newRows.slice(0, newRows.length));
510 if (this.attr) this.attr = this.attr.concat( newAttr.slice(0, newAttr.length));
511 if (this.rows.length > this.maxBufferSize) {
512 var fullSize = this.rows.length;
513 this.rows = this.rows.slice(this.rows.length - this.maxBufferSize, this.rows.length);
514 if (this.attr) this.attr = this.attr.slice(this.attr.length - this.maxBufferSize, this.attr.length);
515 this.startPos = this.startPos + (fullSize - this.rows.length);
518 } else { //prepending
519 if (start + newRows.length < this.startPos) {
522 this.rows = newRows.slice(0, this.startPos).concat(this.rows);
523 if (this.maxBufferSize && this.rows.length > this.maxBufferSize)
524 this.rows = this.rows.slice(0, this.maxBufferSize);
526 this.startPos = start;
528 this.size = this.rows.length;
531 sortBuffer: function(colnum) {
533 var col=this.liveGrid.columns[colnum];
534 if (this.options.sortParmFmt) {
535 this.sortParm['sort_col']=col[this.options.sortParmFmt];
536 this.sortParm['sort_dir']=col.getSortDirection();
538 this.sortParm['s'+colnum]=col.getSortDirection();
543 printAllSQL: function(exportType) {
544 var parms=this.formQueryHashSQL(0,this.liveGrid.options.maxPrint,exportType);
545 parms.hidden=this.liveGrid.listInvisible('index').join(',');
546 var url=this.dataSource+'?'+Rico.toQueryString(parms);
547 window.open(url,'',this.liveGrid.options.exportWindow);
550 printVisibleSQL: function(exportType) {
551 var parms=this.formQueryHashSQL(this.liveGrid.contentStartPos-1, this.liveGrid.pageSize, exportType);
552 parms.hidden=this.liveGrid.listInvisible('index').join(',');
553 var url=this.dataSource+'?'+Rico.toQueryString(parms);
554 window.open(url,'',this.liveGrid.options.exportWindow);
557 // for datasource that is a javascript function
558 _printAll: function() {
559 this.liveGrid.exportStart();
560 this.ajaxOptions.parameters = this.formQueryHashSQL(0,this.liveGrid.options.maxPrint);
562 this.ajaxOptions.onComplete = function() { self._jsExport(); };
563 this.dataSource(this.ajaxOptions);
566 _jsExport: function(newRows, newAttr, totalRows, errMsg) {
567 Rico.log("_jsExport: "+arguments.length);
569 Rico.log("_jsExport: received error="+errMsg);
570 this.liveGrid.showMsg(Rico.getPhraseById("requestError",errMsg));
573 this.exportBuffer(newRows,0);
574 this.liveGrid.exportFinish();