1/** 2 * JsHttpRequest: JavaScript "AJAX" data loader (form support only!) 3 * 4 * @license LGPL 5 * @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/ 6 * @version 5.x $Id$ 7 */ 8// {{{ 9function JsHttpRequest() { 10 // Standard properties. 11 var t = this; 12 t.onreadystatechange = null; 13 t.readyState = 0; 14 t.responseText = null; 15 t.responseXML = null; 16 t.status = 200; 17 t.statusText = "OK"; 18 // JavaScript response array/hash 19 t.responseJS = null; 20 21 // Additional properties. 22 t.caching = false; // need to use caching? 23 t.loader = null; // loader to use ('form', 'script', 'xml'; null - autodetect) 24 t.session_name = "PHPSESSID"; // set to SID cookie or GET parameter name 25 26 // Internals. 27 t._ldObj = null; // used loader object 28 t._reqHeaders = []; // collected request headers 29 t._openArgs = null; // parameters from open() 30 t._errors = { 31 inv_form_el: 'Invalid FORM element detected: name=%, tag=%', 32 must_be_single_el: 'If used, <form> must be a single HTML element in the list.', 33 js_invalid: 'JavaScript code generated by backend is invalid!\n%', 34 url_too_long: 'Cannot use so long query with GET request (URL is larger than % bytes)', 35 unk_loader: 'Unknown loader: %', 36 no_loaders: 'No loaders registered at all, please check JsHttpRequest.LOADERS array', 37 no_loader_matched: 'Cannot find a loader which may process the request. Notices are:\n%', 38 no_headers: 'Method setRequestHeader() cannot work together with the % loader.' 39 } 40 41 /** 42 * Aborts the request. Behaviour of this function for onreadystatechange() 43 * is identical to IE (most universal and common case). E.g., readyState -> 4 44 * on abort() after send(). 45 */ 46 t.abort = function() { with (this) { 47 if (_ldObj && _ldObj.abort) _ldObj.abort(); 48 _cleanup(); 49 if (readyState == 0) { 50 // start->abort: no change of readyState (IE behaviour) 51 return; 52 } 53 if (readyState == 1 && !_ldObj) { 54 // open->abort: no onreadystatechange call, but change readyState to 0 (IE). 55 // send->abort: change state to 4 (_ldObj is not null when send() is called) 56 readyState = 0; 57 return; 58 } 59 _changeReadyState(4, true); // 4 in IE & FF on abort() call; Opera does not change to 4. 60 }} 61 62 /** 63 * Prepares the object for data loading. 64 */ 65 t.open = function(method, url, asyncFlag, username, password) { with (this){ 66 // Append SID to original URL. Use try...catch for security problems. 67 try { 68 if ( 69 document.location.search.match(new RegExp('[&?]' + session_name + '=([^&?]*)')) 70 || document.cookie.match(new RegExp('(?:;|^)\\s*' + session_name + '=([^;]*)')) 71 ) { 72 url += (url.indexOf('?') >= 0? '&' : '?') + session_name + "=" + this.escape(RegExp.$1); 73 } 74 } catch (e) {} 75 // Store open arguments to hash. 76 _openArgs = { 77 method: (method || '').toUpperCase(), 78 url: url, 79 asyncFlag: asyncFlag, 80 username: username != null? username : '', 81 password: password != null? password : '' 82 } 83 _ldObj = null; 84 _changeReadyState(1, true); // compatibility with XMLHttpRequest 85 return true; 86 }} 87 88 /** 89 * Sends a request to a server. 90 */ 91 t.send = function(content) { 92 if (!this.readyState) { 93 // send without open or after abort: no action (IE behaviour). 94 return; 95 } 96 this._changeReadyState(1, true); // compatibility with XMLHttpRequest 97 this._ldObj = null; 98 99 // Prepare to build QUERY_STRING from query hash. 100 var queryText = []; 101 var queryElem = []; 102 if (!this._hash2query(content, null, queryText, queryElem)) return; 103 104 // Solve the query hashcode & return on cache hit. 105 var hash = null; 106 if (this.caching && !queryElem.length) { 107 hash = this._openArgs.username + ':' + this._openArgs.password + '@' + this._openArgs.url + '|' + queryText + "#" + this._openArgs.method; 108 var cache = JsHttpRequest.CACHE[hash]; 109 if (cache) { 110 this._dataReady(cache[0], cache[1]); 111 return false; 112 } 113 } 114 115 // Try all the loaders. 116 var loader = (this.loader || '').toLowerCase(); 117 if (loader && !JsHttpRequest.LOADERS[loader]) return this._error('unk_loader', loader); 118 var errors = []; 119 var lds = JsHttpRequest.LOADERS; 120 for (var tryLoader in lds) { 121 var ldr = lds[tryLoader].loader; 122 if (!ldr) continue; // exclude possibly derived prototype properties from "for .. in". 123 if (loader && tryLoader != loader) continue; 124 // Create sending context. 125 var ldObj = new ldr(this); 126 JsHttpRequest.extend(ldObj, this._openArgs); 127 JsHttpRequest.extend(ldObj, { 128 queryText: queryText.join('&'), 129 queryElem: queryElem, 130 id: (new Date().getTime()) + "" + JsHttpRequest.COUNT++, 131 hash: hash, 132 span: null 133 }); 134 var error = ldObj.load(); 135 if (!error) { 136 // Save loading script. 137 this._ldObj = ldObj; 138 JsHttpRequest.PENDING[ldObj.id] = this; 139 return true; 140 } 141 if (!loader) { 142 errors[errors.length] = '- ' + tryLoader.toUpperCase() + ': ' + this._l(error); 143 } else { 144 return this._error(error); 145 } 146 } 147 148 // If no loader matched, generate error message. 149 return tryLoader? this._error('no_loader_matched', errors.join('\n')) : this._error('no_loaders'); 150 } 151 152 /** 153 * Returns all response headers (if supported). 154 */ 155 t.getAllResponseHeaders = function() { with (this) { 156 return _ldObj && _ldObj.getAllResponseHeaders? _ldObj.getAllResponseHeaders() : []; 157 }} 158 159 /** 160 * Returns one response header (if supported). 161 */ 162 t.getResponseHeader = function(label) { with (this) { 163 return _ldObj && _ldObj.getResponseHeader? _ldObj.getResponseHeader() : []; 164 }} 165 166 /** 167 * Adds a request header to a future query. 168 */ 169 t.setRequestHeader = function(label, value) { with (this) { 170 _reqHeaders[_reqHeaders.length] = [label, value]; 171 }} 172 173 // 174 // Internal functions. 175 // 176 177 /** 178 * Do all the work when a data is ready. 179 */ 180 t._dataReady = function(text, js) { with (this) { 181 if (caching && _ldObj) JsHttpRequest.CACHE[_ldObj.hash] = [text, js]; 182 if (text !== null || js !== null) { 183 status = 4; 184 responseText = responseXML = text; 185 responseJS = js; 186 } else { 187 status = 500; 188 responseText = responseXML = responseJS = null; 189 } 190 _changeReadyState(2); 191 _changeReadyState(3); 192 _changeReadyState(4); 193 _cleanup(); 194 }} 195 196 /** 197 * Analog of sprintf(), but translates the first parameter by _errors. 198 */ 199 t._l = function(args) { 200 var i = 0, p = 0, msg = this._errors[args[0]]; 201 // Cannot use replace() with a callback, because it is incompatible with IE5. 202 while ((p = msg.indexOf('%', p)) >= 0) { 203 var a = args[++i] + ""; 204 msg = msg.substring(0, p) + a + msg.substring(p + 1, msg.length); 205 p += 1 + a.length; 206 } 207 return msg; 208 } 209 210 /** 211 * Called on error. 212 */ 213 t._error = function(msg) { 214 msg = this._l(typeof(msg) == 'string'? arguments : msg) 215 msg = "JsHttpRequest: " + msg; 216 if (!window.Error) { 217 // Very old browser... 218 throw msg; 219 } else if ((new Error(1, 'test')).description == "test") { 220 // We MUST (!!!) pass 2 parameters to the Error() constructor for IE5. 221 throw new Error(1, msg); 222 } else { 223 // Mozilla does not support two-parameter call style. 224 throw new Error(msg); 225 } 226 } 227 228 /** 229 * Convert hash to QUERY_STRING. 230 * If next value is scalar or hash, push it to queryText. 231 * If next value is form element, push [name, element] to queryElem. 232 */ 233 t._hash2query = function(content, prefix, queryText, queryElem) { 234 if (prefix == null) prefix = ""; 235 if((''+typeof(content)).toLowerCase() == 'object') { 236 var formAdded = false; 237 if (content && content.parentNode && content.parentNode.appendChild && content.tagName && content.tagName.toUpperCase() == 'FORM') { 238 content = { form: content }; 239 } 240 for (var k in content) { 241 var v = content[k]; 242 if (v instanceof Function) continue; 243 var curPrefix = prefix? prefix + '[' + this.escape(k) + ']' : this.escape(k); 244 var isFormElement = v && v.parentNode && v.parentNode.appendChild && v.tagName; 245 if (isFormElement) { 246 var tn = v.tagName.toUpperCase(); 247 if (tn == 'FORM') { 248 // FORM itself is passed. 249 formAdded = true; 250 } else if (tn == 'INPUT' || tn == 'TEXTAREA' || tn == 'SELECT') { 251 // This is a single form elemenent. 252 } else { 253 return this._error('inv_form_el', (v.name||''), v.tagName); 254 } 255 queryElem[queryElem.length] = { name: curPrefix, e: v }; 256 } else if (v instanceof Object) { 257 this._hash2query(v, curPrefix, queryText, queryElem); 258 } else { 259 // We MUST skip NULL values, because there is no method 260 // to pass NULL's via GET or POST request in PHP. 261 if (v === null) continue; 262 queryText[queryText.length] = curPrefix + "=" + this.escape('' + v); 263 } 264 if (formAdded && queryElem.length > 1) { 265 return this._error('must_be_single_el'); 266 } 267 } 268 } else { 269 queryText[queryText.length] = content; 270 } 271 return true; 272 } 273 274 /** 275 * Remove last used script element (clean memory). 276 */ 277 t._cleanup = function() { 278 var ldObj = this._ldObj; 279 if (!ldObj) return; 280 // Mark this loading as aborted. 281 JsHttpRequest.PENDING[ldObj.id] = false; 282 var span = ldObj.span; 283 if (!span) return; 284 ldObj.span = null; 285 var closure = function() { 286 span.parentNode.removeChild(span); 287 } 288 // IE5 crashes on setTimeout(function() {...}, ...) construction! Use tmp variable. 289 JsHttpRequest.setTimeout(closure, 50); 290 } 291 292 /** 293 * Change current readyState and call trigger method. 294 */ 295 t._changeReadyState = function(s, reset) { with (this) { 296 if (reset) { 297 status = statusText = responseJS = null; 298 responseText = ''; 299 } 300 readyState = s; 301 if (onreadystatechange) onreadystatechange(); 302 }} 303 304 /** 305 * JS escape() does not quote '+'. 306 */ 307 t.escape = function(s) { 308 return escape(s).replace(new RegExp('\\+','g'), '%2B'); 309 } 310} 311 312 313// Global library variables. 314JsHttpRequest.COUNT = 0; // unique ID; used while loading IDs generation 315JsHttpRequest.MAX_URL_LEN = 2000; // maximum URL length 316JsHttpRequest.CACHE = {}; // cached data 317JsHttpRequest.PENDING = {}; // pending loadings 318JsHttpRequest.LOADERS = {}; // list of supported data loaders (filled at the bottom of the file) 319JsHttpRequest._dummy = function() {}; // avoid memory leaks 320 321 322/** 323 * These functions are dirty hacks for IE 5.0 which does not increment a 324 * reference counter for an object passed via setTimeout(). So, if this 325 * object (closure function) is out of scope at the moment of timeout 326 * applying, IE 5.0 crashes. 327 */ 328 329/** 330 * Timeout wrappers storage. Used to avoid zeroing of referece counts in IE 5.0. 331 * Please note that you MUST write "window.setTimeout", not "setTimeout", else 332 * IE 5.0 crashes again. Strange, very strange... 333 */ 334JsHttpRequest.TIMEOUTS = { s: window.setTimeout, c: window.clearTimeout }; 335 336/** 337 * Wrapper for IE5 buggy setTimeout. 338 * Use this function instead of a usual setTimeout(). 339 */ 340JsHttpRequest.setTimeout = function(func, dt) { 341 // Always save inside the window object before a call (for FF)! 342 window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.s; 343 if (typeof(func) == "string") { 344 id = window.JsHttpRequest_tmp(func, dt); 345 } else { 346 var id = null; 347 var mediator = function() { 348 func(); 349 delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference 350 } 351 id = window.JsHttpRequest_tmp(mediator, dt); 352 // Store a reference to the mediator function to the global array 353 // (reference count >= 1); use timeout ID as an array key; 354 JsHttpRequest.TIMEOUTS[id] = mediator; 355 } 356 window.JsHttpRequest_tmp = null; // no delete() in IE5 for window 357 return id; 358} 359 360/** 361 * Complimental wrapper for clearTimeout. 362 * Use this function instead of usual clearTimeout(). 363 */ 364JsHttpRequest.clearTimeout = function(id) { 365 window.JsHttpRequest_tmp = JsHttpRequest.TIMEOUTS.c; 366 delete JsHttpRequest.TIMEOUTS[id]; // remove circular reference 367 var r = window.JsHttpRequest_tmp(id); 368 window.JsHttpRequest_tmp = null; // no delete() in IE5 for window 369 return r; 370} 371 372 373/** 374 * Global static function. 375 * Simple interface for most popular use-cases. 376 * You may also pass URLs like "GET url" or "script.GET url". 377 */ 378JsHttpRequest.query = function(url, content, onready, nocache) { 379 var req = new this(); 380 req.caching = !nocache; 381 req.onreadystatechange = function() { 382 if (req.readyState == 4) { 383 onready(req.responseJS, req.responseText); 384 } 385 } 386 var method = null; 387 if (url.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)) { 388 req.loader = RegExp.$2? RegExp.$2 : null; 389 method = RegExp.$3; 390 url = RegExp.$4; 391 } 392 req.open(method, url, true); 393 req.send(content); 394} 395 396 397/** 398 * Global static function. 399 * Called by server backend script on data load. 400 */ 401JsHttpRequest.dataReady = function(d) { 402 var th = this.PENDING[d.id]; 403 delete this.PENDING[d.id]; 404 if (th) { 405 th._dataReady(d.text, d.js); 406 } else if (th !== false) { 407 throw "dataReady(): unknown pending id: " + d.id; 408 } 409} 410 411 412// Adds all the properties of src to dest. 413JsHttpRequest.extend = function(dest, src) { 414 for (var k in src) dest[k] = src[k]; 415} 416 417/** 418 * Each loader has the following properties which must be initialized: 419 * - method 420 * - url 421 * - asyncFlag (ignored) 422 * - username 423 * - password 424 * - queryText (string) 425 * - queryElem (array) 426 * - id 427 * - hash 428 * - span 429 */ 430 431// }}} 432 433// {{{ form 434// Loader: FORM & IFRAME. 435// [+] Supports file uploading. 436// [+] GET and POST methods are supported. 437// [+] Supports loading from different domains. 438// [-] Uses a lot of system resources. 439// [-] Backend data cannot be browser-cached. 440// [-] Pollutes browser history on some old browsers. 441// 442JsHttpRequest.LOADERS.form = { loader: function(req) { 443 JsHttpRequest.extend(req._errors, { 444 form_el_not_belong: 'Element "%" does not belong to any form!', 445 form_el_belong_diff: 'Element "%" belongs to a different form. All elements must belong to the same form!', 446 form_el_inv_enctype: 'Attribute "enctype" of the form must be "%" (for IE), "%" given.' 447 }) 448 449 this.load = function() { 450 var th = this; 451 452 if (!th.method) th.method = 'POST'; 453 th.url += (th.url.indexOf('?') >= 0? '&' : '?') + 'JsHttpRequest=' + th.id + '-' + 'form'; 454 455 if (req._reqHeaders.length) return ['no_headers', 'FORM']; 456 457 // If GET, build full URL. Then copy QUERY_STRING to queryText. 458 if (th.method == 'GET') { 459 if (th.queryText) th.url += (th.url.indexOf('?') >= 0? '&' : '?') + th.queryText; 460 if (th.url.length > JsHttpRequest.MAX_URL_LEN) return ['url_too_long', JsHttpRequest.MAX_URL_LEN]; 461 var p = th.url.split('?', 2); 462 th.url = p[0]; 463 th.queryText = p[1] || ''; 464 } 465 466 // Check if all form elements belong to same form. 467 var form = null; 468 var wholeFormSending = false; 469 if (th.queryElem.length) { 470 if (th.queryElem[0].e.tagName.toUpperCase() == 'FORM') { 471 // Whole FORM sending. 472 form = th.queryElem[0].e; 473 wholeFormSending = true; 474 th.queryElem = []; 475 } else { 476 // If we have at least one form element, we use its FORM as a POST container. 477 form = th.queryElem[0].e.form; 478 // Validate all the elements. 479 for (var i = 0; i < th.queryElem.length; i++) { 480 var e = th.queryElem[i].e; 481 if (!e.form) { 482 return ['form_el_not_belong', e.name]; 483 } 484 if (e.form != form) { 485 return ['form_el_belong_diff', e.name]; 486 } 487 } 488 } 489 490 // Check enctype of the form. 491 if (th.method == 'POST') { 492 var need = "multipart/form-data"; 493 var given = (form.attributes.encType && form.attributes.encType.nodeValue) || (form.attributes.enctype && form.attributes.enctype.value) || form.enctype; 494 if (given != need) { 495 return ['form_el_inv_enctype', need, given]; 496 } 497 } 498 } 499 500 // Create invisible IFRAME with temporary form (form is used on empty queryElem). 501 // We ALWAYS create th IFRAME in the document of the form - for Opera 7.20. 502 var d = form && (form.ownerDocument || form.document) || document; 503 var ifname = 'jshr_i_' + th.id; 504 var s = th.span = d.createElement('DIV'); 505 s.style.position = 'absolute'; 506 s.style.display = 'none'; 507 s.style.visibility = 'hidden'; 508 s.innerHTML = 509 (form? '' : '<form' + (th.method == 'POST'? ' enctype="multipart/form-data" method="post"' : '') + '></form>') + // stupid IE, MUST use innerHTML assignment :-( 510 '<iframe name="' + ifname + '" id="' + ifname + '" style="width:0px; height:0px; overflow:hidden; border:none"></iframe>' 511 if (!form) { 512 form = th.span.firstChild; 513 } 514 515 // Insert generated form inside the document. 516 // Be careful: don't forget to close FORM container in document body! 517 d.body.insertBefore(s, d.body.lastChild); 518 519 // Function to safely set the form attributes. Parameter attr is NOT a hash 520 // but an array, because "for ... in" may badly iterate over derived attributes. 521 var setAttributes = function(e, attr) { 522 var sv = []; 523 var form = e; 524 // This strange algorythm is needed, because form may contain element 525 // with name like 'action'. In IE for such attribute will be returned 526 // form element node, not form action. Workaround: copy all attributes 527 // to new empty form and work with it, then copy them back. This is 528 // THE ONLY working algorythm since a lot of bugs in IE5.0 (e.g. 529 // with e.attributes property: causes IE crash). 530 if (e.mergeAttributes) { 531 var form = d.createElement('form'); 532 form.mergeAttributes(e, false); 533 } 534 for (var i = 0; i < attr.length; i++) { 535 var k = attr[i][0], v = attr[i][1]; 536 // TODO: http://forum.dklab.ru/viewtopic.php?p=129059#129059 537 sv[sv.length] = [k, form.getAttribute(k)]; 538 form.setAttribute(k, v); 539 } 540 if (e.mergeAttributes) { 541 e.mergeAttributes(form, false); 542 } 543 return sv; 544 } 545 546 // Run submit with delay - for old Opera: it needs some time to create IFRAME. 547 var closure = function() { 548 // Save JsHttpRequest object to new IFRAME. 549 top.JsHttpRequestGlobal = JsHttpRequest; 550 551 // Disable ALL the form elements. 552 var savedNames = []; 553 if (!wholeFormSending) { 554 for (var i = 0, n = form.elements.length; i < n; i++) { 555 savedNames[i] = form.elements[i].name; 556 form.elements[i].name = ''; 557 } 558 } 559 560 // Insert hidden fields to the form. 561 var qt = th.queryText.split('&'); 562 for (var i = qt.length - 1; i >= 0; i--) { 563 var pair = qt[i].split('=', 2); 564 var e = d.createElement('INPUT'); 565 e.type = 'hidden'; 566 e.name = unescape(pair[0]); 567 e.value = pair[1] != null? unescape(pair[1]) : ''; 568 form.appendChild(e); 569 } 570 571 572 // Change names of along user-passed form elements. 573 for (var i = 0; i < th.queryElem.length; i++) { 574 th.queryElem[i].e.name = th.queryElem[i].name; 575 } 576 577 // Temporary modify form attributes, submit form, restore attributes back. 578 var sv = setAttributes( 579 form, 580 [ 581 ['action', th.url], 582 ['method', th.method], 583 ['onsubmit', null], 584 ['target', ifname] 585 ] 586 ); 587 form.submit(); 588 setAttributes(form, sv); 589 590 // Remove generated temporary hidden elements from the top of the form. 591 for (var i = 0; i < qt.length; i++) { 592 // Use "form.firstChild.parentNode", not "form", or IE5 crashes! 593 form.lastChild.parentNode.removeChild(form.lastChild); 594 } 595 // Enable all disabled elements back. 596 if (!wholeFormSending) { 597 for (var i = 0, n = form.elements.length; i < n; i++) { 598 form.elements[i].name = savedNames[i]; 599 } 600 } 601 } 602 JsHttpRequest.setTimeout(closure, 100); 603 604 // Success. 605 return null; 606 } 607}} 608// }}}