JS IE11 - re-write localStorage is null - javascript

I use the script from user4822973 in Post localStorage object is undefined in IE.
But I still have the problem in the IE-11, when I re-write the storage, all data is null. With Firefox and Opera there is no problem.
// Check 'local storage'
!localStorage && (l = location, p = l.pathname.replace(/(^..)(:)/, "$1$$"), (l.href = l.protocol + "//127.0.0.1" + p));
if (typeof(Storage) != "undefined") {
var myObj = JSON.parse(localStorage.getItem("multipleData"));
alert(myObj);
if (!myObj || 0 === myObj.length){
//default values
document.getElementById("reason").value = reason;
document.getElementById("mailTo").value = mailTo;
document.getElementById("mailCc").value = mailCc;
document.getElementById("workStart").value = workStart;
document.getElementById("workEnd").value = workEnd;
}
else{
var myObjReason = myObj["reason"];
var myObjMailTo = myObj["mailTo"];
var myObjMailCc = myObj["mailCc"];
var myObjWorkStart = myObj["workStart"];
var myObjWorkEnd = myObj["workEnd"];
...
//Write to storage
function saveLocalStorage(){
var multipleData = {"reason" : document.getElementById("reason").value , "mailTo" : document.getElementById("mailTo").value , "mailCc" : document.getElementById("mailCc").value , "workStart" : document.getElementById("workStart").value, "workEnd" : document.getElementById("workEnd").value};
localStorage.setItem("multipleData", JSON.stringify(multipleData));
}

Related

One spreadsheet for each user

I have a code in GAS that works with a spreadsheet at the background and it works for a single use simultaneously.
The problem is that I want to create a copy of the spreadsheet, at the beginning of the code, for the interaction with every user that enter at the web App.
I tried two possibilities:
Create the duplicate at the beginning of the main.js in order to be recognized as global variable for every function in the code, but the code creates repetitive files when I interact with any element at the web page because Javascript read the codes with every interaction.
Create the duplicate within DoGet function creating at the end a variable linked to the Id or to the new file, but the rest of functions don't recognized that variable like a global variable, even declaring the variable at the beginning of the main.js
Code
var x;
if(x == null){
var myArray = crearnuevoarchivo(x);
x = myArray[0];
var database = myArray[1];
}
const sheetConfiguracion = database.getSheetByName("Configuracion");
var lastRowProgramas = lastRowForColumn(sheetConfiguracion, 18);
var lastRowMandos = lastRowForColumn(sheetConfiguracion, 12);
const sheetTipos = database.getSheetByName("Tipos");
var lastRowTipos = sheetTipos.getLastRow();
const sheetSolicitud = database.getSheetByName("Solicitud");
const registro_peticiones = SpreadsheetApp.openById('xxxxxxxxxxxxxx');
const sheetRegistro = registro_peticiones.getSheetByName("Registro");
const sheetHerramientas = database.getSheetByName("Herramientas");
var lastRowHerramientas = lastRowForColumn(sheetHerramientas, 1);
const sheetSolicitudFOD = database.getSheetByName("Solicitud_FOD");
const sheetfotosID = database.getSheetByName("FotosID");
function crearnuevoarchivo(x){
if(x == null){
const database2 = SpreadsheetApp.openById('xxxxxxxxxxxxxx');
var hoyarchivo = new Date();
var mesarchivo = hoyarchivo.getMonth() + 1;
var fechaarchivo = mesarchivo+"/"+hoyarchivo.getFullYear();
const databaseID = DriveApp.getFileById('xxxxxxxxxx').makeCopy('database '+fechaarchivo, DriveApp.getFolderById('xxxxxxxxxxxxx')).getId();
var database = SpreadsheetApp.openById(databaseID);
x = 1;
var myArray = new Array(2);
myArray[0] = x;
myArray[1] = database;
return myArray
}
}
var rutaWeb = ScriptApp.getService().getUrl();
function doGet(e) {
if(e.parameter.p){
var page = e.parameter.p;
if(page == "noFOD"){
var hojas = database.getSheets();
var nuevaSheet = hojas.pop();
var valor = nuevaSheet.getRange(2, 14).getValue();
return HtmlService.createTemplateFromFile(page).evaluate();
}
else{
if(page == "catalogo"){
var hojas = database.getSheets();
var nuevaSheet = hojas.pop();
nuevaSheet.getRange(3, 14).setValue(1);
var valor = nuevaSheet.getRange(3, 14).getValue();
return HtmlService.createTemplateFromFile(page).evaluate();
}
if(page == "index"){
var hojas = database.getSheets();
var nuevaSheet = hojas.pop();
var valor = nuevaSheet.getRange(5, 14).getValue();
var r = 5;
borrar_registro_noFOD();
borrar_registro_FOD()
return HtmlService.createTemplateFromFile(page).evaluate();
}
if(page == "FOD"){
var hojas = database.getSheets();
var nuevaSheet = hojas.pop();
var valor = nuevaSheet.getRange(4, 14).getValue();
var r = 4;
return HtmlService.createTemplateFromFile(page).evaluate();
}
if(page == "catalogoFOD"){
var hojas = database.getSheets();
var nuevaSheet = hojas.pop();
var r = 6;
nuevaSheet.getRange(6, 14).setValue(r)
return HtmlService.createTemplateFromFile(page).evaluate();
}
}
}else{
var out = new Array()
var sheets = database.getSheets();
for (var i=12 ; i < sheets.length ; i++){
var sheet= database.getSheetByName(sheets[i].getName());
database.deleteSheet(sheet);
}
const sheetTipos = database.getSheetByName("Tipos");
sheetTipos.copyTo(database);
var hojas = database.getSheets();
var nuevaSheet = hojas.pop();
nuevaSheet.getRange(2, 14).setValue(0);
nuevaSheet.getRange(3, 14).setValue(0);
nuevaSheet.getRange(4, 14).setValue(0);
nuevaSheet.getRange(5, 14).setValue(0);
nuevaSheet.getRange(1, 14, 7, 1).clearContent();
nuevaSheet.getRange(2, 14, 6, 1).setValue(0);
nuevaSheet.getRange(1, 15, 100, 7).clearContent();
borrar_registro_noFOD(database);
borrar_registro_FOD(database)
var x = 1;
var page = "index";
}
return HtmlService.createTemplateFromFile(page).evaluate();
}
Example of parameters that I'm passing from Index.html
/* <a href="<?!= rutaWeb + '?p=noFOD' ?>" */
Global variables in Apps Script are different from global variables in other programming languages.
A way of storing global variables is making use of the PropertiesService class in Apps Script and using:
setProperty(key, value) - for storing the key-value pair;
getProperty(key) - for retrieving the value associated with the key.
Reference
Apps Script Properties Class.

How to show popup error in Point of Sale in odoo 12

I want to restrict the user from adding more product to sell if the order is tag as booked order
I want to show popup error message when it is booked order and the user still click the product
here is my code
odoo.define('tw_pos_inherit_model.attemptInherit', function (require) {
"use strict";
var POSInheritmodel = require('point_of_sale.models');
var ajax = require('web.ajax');
var BarcodeParser = require('barcodes.BarcodeParser');
var PosDB = require('point_of_sale.DB');
var devices = require('point_of_sale.devices');
var concurrency = require('web.concurrency');
var config = require('web.config');
var core = require('web.core');
var field_utils = require('web.field_utils');
var rpc = require('web.rpc');
var session = require('web.session');
var time = require('web.time');
var utils = require('web.utils');
var gui = require('point_of_sale.gui');
var orderline_id = 1;
var QWeb = core.qweb;
var _t = core._t;
var Mutex = concurrency.Mutex;
var round_di = utils.round_decimals;
var round_pr = utils.round_precision;
var _super_order = POSInheritmodel.Order.prototype;
POSInheritmodel.Order = POSInheritmodel.Order.extend({
add_product: function(product, options){
var can_add = true;
var changes = this.pos.get_order();
var self = this;
try{
if(changes.selected_orderline.order.quotation_ref.book_order){
can_add= false;
}
}catch(err){}
if (can_add){
if(this._printed){
this.destroy();
return this.pos.get_order().add_product(product, options);
}
this.assert_editable();
options = options || {};
var attr = JSON.parse(JSON.stringify(product));
attr.pos = this.pos;
attr.order = this;
var line = new POSInheritmodel.Orderline({}, {pos: this.pos, order: this, product: product});
if(options.quantity !== undefined){
line.set_quantity(options.quantity);
}
if(options.price !== undefined){
line.set_unit_price(options.price);
}
//To substract from the unit price the included taxes mapped by the fiscal position
this.fix_tax_included_price(line);
if(options.discount !== undefined){
line.set_discount(options.discount);
}
if(options.discount_percentage !== undefined){
line.set_if_discount_percentage(options.discount_percentage);
}
if(options.discount_amount !== undefined){
line.set_if_discount_amount(options.discount_amount);
}
if(options.extras !== undefined){
for (var prop in options.extras) {
line[prop] = options.extras[prop];
}
}
var to_merge_orderline;
for (var i = 0; i < this.orderlines.length; i++) {
if(this.orderlines.at(i).can_be_merged_with(line) && options.merge !== false){
to_merge_orderline = this.orderlines.at(i);
}
}
if (to_merge_orderline){
to_merge_orderline.merge(line);
} else {
this.orderlines.add(line);
}
this.select_orderline(this.get_last_orderline());
if(line.has_product_lot){
this.display_lot_popup();
}
}else{
self.gui.show_popup('error',{
title :_t('Modification Resctricted'),
body :_t('Booked Order cannot be modified'),
});
}
},
});
});
but im getting an error
Uncaught TypeError: Cannot read property 'show_popup' of undefined
http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:475
Traceback:
TypeError: Cannot read property 'show_popup' of undefined
at child.add_product (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:475:116)
at Class.click_product (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:326:257)
at Object.click_product_action (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:325:951)
at HTMLElement.click_product_handler (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:320:1738)
im sorry im really confuse do i still need to initialized the this.gui first?
even though i have var gui = require('point_of_sale.gui'); initialized already
when i log the this.gui to my console the output is undefined
You can access gui via posModel.
self.pos.gui.show_popup('error',{
title :_t('Modification Resctricted'),
body :_t('Booked Order cannot be modified'),
});
You can check an example at connect_to_proxy

How do I make the right conditions for the url based on the value of a variable? (javascript)

My script javascript like this :
<script>
var url = 'http://my-app.test/item';
var sessionBrand = 'honda';
var sessionModel = 'jazz';
var sessionCategory = 'velg';
var sessionKeyword = 'RS 175/60 R 15';
if(sessionBrand)
var brand = '?brand='+sessionBrand;
else
var brand = '';
if(sessionModel)
var model = '&model='+sessionModel;
else
var model = '';
if(sessionCategory)
var category = '&category='+sessionCategory;
else
var category = '';
if(sessionKeyword)
var keyword = '&keyword='+this.sessionKeyword;
else
var keyword = '';
var newUrl = url+brand+model+category+keyword;
console.log(newUrl);
</script>
The result of console.log like this :
http://my-app.test/item?brand=honda&model=jazz&category=velg&keyword=RS 175/60 R 15
var sessionBrand, sessionModel, sessionCategory and sessionKeyword is dynamic. It can change. It can be null or it can have value
I have a problem
For example the case like this :
var sessionBrand = '';
var sessionModel = '';
var sessionCategory = '';
var sessionKeyword = 'RS 175/60 R 15';
The url to be like this :
http://my-app.test/item&keyword=RS 175/60 R 15
Should the url like this :
http://my-app.test/item?keyword=RS 175/60 R 15
I'm still confused to make the condition
How can I solve this problem?
Just use the array for params and then join them with & separator. For example:
var url = 'http://my-app.test/item';
var sessionBrand = 'honda';
var sessionModel = 'jazz';
var sessionCategory = 'velg';
var sessionKeyword = 'RS 175/60 R 15';
var params = [];
if (sessionBrand) {
params.push('brand=' + sessionBrand);
}
if (sessionModel) {
params.push('model=' + sessionModel);
}
if(sessionCategory) {
params.push('category=' + sessionCategory);
}
if(sessionKeyword) {
params.push('category=' + sessionCategory);
}
var newUrl = url + '?' + params.join('&');
console.log(newUrl);
The problem with your code is that it is prefacing all query parameters with a & - except for the sessionBrand. What you need in a URL is for the first parameter to start with a ?, and all others with a &. As you saw, your code doesn't do this when there is no sessionBrand.
There are number of ways to fix this. Probably the neatest I can think of is to assemble the various parts as you are, but without any prefixes - then join them all together at the end. Like this (I just saw Viktor's solution, it's exactly the same idea, but neater because he rewrote more of your earlier code):
if(sessionBrand)
var brand = 'brand='+sessionBrand;
else
var brand = '';
if(sessionModel)
var model = 'model='+sessionModel;
else
var model = '';
if(sessionCategory)
var category = 'category='+sessionCategory;
else
var category = '';
if(sessionKeyword)
var keyword = 'keyword='+this.sessionKeyword;
else
var keyword = '';
var queryString = '?' + [sessionBrand, sessionModel, sessionCategory, sessionKeyword].filter(function(str) {
return str.length > 0;
}).join("&");
var newUrl = url+queryString;

How to remove some parameters from an URL string?

I have this var storing a string that represents a URL full of parameters. I'm using AngularJS, and I'm not sure if there is any useful module (or maybe with plain JavaScript) to remove the unneeded URL parameters without having to use regex?
For example I need to remove &month=05 and also &year=2017 from:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
Use the URLSearchParams API:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
var urlParts = url.split('?');
var params = new URLSearchParams(urlParts[1]);
params.delete('month');
params.delete('year')
var newUrl = urlParts[0] + '?' + params.toString()
console.log(newUrl);
The advantage of using this API is that it works with and creates strings with correct percent encoding.
For more information, see MDN Developer Reference - URLSearchParams API.
You can use this function that take 2 parameters: the param you are trying to remove and your source URL:
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var url2 = removeParam("month", url);
var url3 = removeParam("year", url2);
console.log(url3);
Alternative solution with a regex
Sure you can use RegExr: ((&)year=([^&]))|((&)month=([^&]))
use:
url = url.replace(/(year=([^&]*))|(month=([^&]*))/g, '');
Read more regex :)...
function removeParam(name, url){
return url.replace('/((&)*' + name + '=([^&]*))/g','');
}
var url = "?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
function removeParam(name, _url){
var reg = new RegExp("((&)*" + name + "=([^&]*))","g");
return _url.replace(reg,'');
}
url = removeParam('year', url);
url = removeParam('month', url);
document.getElementById('url-replace').innerHTML = url;
<div id="url-replace"></div>
Using string replace:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var modifiedUrl = url.replace('&month=05','').replace('&year=2017','');
console.log(modifiedUrl);
You can use the library https://www.npmjs.com/package/query-string
Convert the params to an object and then just use delete params.year delete params.month and convert it back and add it to the original url
const queryString = require('query-string');
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
console.log(location.hash);
//=> '#token=bada55cafe'
const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'
Enhnaced #Mistalis's answer.
Return the value of the last occurrence of a param
Remove the ? of the removed param was the only param
Url encoded the query params to ensure browser stately
function pruneParams(key, url) {
var urlParts = url.split('?');
var rtnUrl = urlParts[0];
var paramParts;
var paramValue;
var params_arr = [];
var queryString = decodeURIComponent(urlParts[1] || '');
if (queryString !== '') {
params_arr = queryString.split('&');
for (var i = params_arr.length - 1; i >= 0; --i) {
paramParts = params_arr[i].split('=');
if (paramParts[0] === key) {
paramValue = paramParts[1];
params_arr.splice(i, 1);
}
}
if (params_arr.length) {
var wasEncoded = url.split('&').length < 2;
rtnUrl = rtnUrl + '?' + (wasEncoded ? encodeURIComponent(params_arr.join('&')) : params_arr.join('&'));
}
}
return { url: rtnUrl, [key]: paramValue, paramCount: params_arr.length > 1 };
}
var u1 = 'http://localhost:4200/member/';
var u2 = 'http://localhost:4200/member/?ts=23423424';
var u3 = 'http://localhost:4200/member/?fooo=2342342asfasf&ts=252523525';
var u4 = 'http://localhost:4200/member?foo=234243&ts=234124124&bar=21kfafjasf&ts=223424234&dd=This Is A Line';
var u5 = 'http://localhost:4200/member?foo%3D234243%26ts%3D2242424%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line';
console.log(pruneParams('ts', u1));
console.log(pruneParams('ts', u2));
console.log(pruneParams('ts', u3));
console.log(pruneParams('ts', u4));
console.log(pruneParams('ts', u5));
// {
// url: 'http://localhost:4200/member/',
// ts: undefined,
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/',
// ts: '23423424',
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/?fooo=2342342asfasf',
// ts: '252523525',
// paramCount: false,
// },
// {
// url: 'http://localhost:4200/member?foo=234243&bar=21kfafjasf&dd=This Is A Line',
// ts: '234124124',
// paramCount: true,
// }
// {
// url: 'http://localhost:4200/member?foo%3D234243%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line',
// ts: '2242424',
// paramCount: true,
// }
Taken from #Mistalis answer but tidied up. Useful if URLSearchParams API is not available.
const removeUrlParam = function (url, param) {
var parts = url.split('?')
url = parts[0]
if (parts.length !== 2) return url
var qs = parts[1]
if (qs === '') return url
var params = qs.split('&')
for (var i = params.length - 1; i >= 0; i -= 1) {
var key = params[i].split('=')[0]
if (key === param) params.splice(i, 1)
}
return params.length ? url + '?' + params.join('&') : url
}
var url1 = removeUrlParam('/xxxxx', 'a')
var url2 = removeUrlParam('/xxxxx?a=1', 'a')
var url3 = removeUrlParam('/xxxxx?a=1&b=2', 'a')
console.log(url1, url2, url3)

Interaction in a Dynamic action between javascript and plsql tasks

I'm trying to execute several pl/sql blocks in a Dynamic Action, with feedback to the end user with a modal dialog reporting the current satus.
Something like:
Processing Step 1...
/*Run pl/sql code for step 1*/
Processing Step 2...
/*Run pl/sql code for Step 2*/
and so on...
Both, the pl/sql and javascript code, run as intended but when I combined them on a Dynamic Action in the sequence:
1 - Execute Javascript
2 - Execute PL/SQL block /* With wait for result option checked*/
3 - Execute Javascript
4 - Execute PL/SQL block
The status dialog is not been shown, however the pl/sql blocks are completed without problems.
I realize that this must be something related to javascript not been multithreaded, so I've moved the pl/sql block to application processes and run them as ajax calls like this:
function something(){
var get;
var result = 0;
updateStatus('Running Step1');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
result = get.get();
if(result > 0){
updateStatus('Running Step 2');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
result = get.get();
}
closeStatusDialog();
}
But still, as before, the processes run fine but the dialog doesn't appear. Finally I added a setTimeOut function to each call, like this:
function something(){
var get;
var result = 0;
updateStatus('Running Step1');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
result = setTimeOut(get.get(),500);
if(result > 0){
updateStatus('Running Step 2');
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
result = setTimeOut(get.get(),500);
}
closeStatusDialog();
}
But still nothing. What can I do to get this running as needed?.
I've checked the browser console and no exeptions are been thrown, likewise with the pl/sql blocks.
I've solved it, although the solution doesn't rely on dynamic actions, just javascript and applicacion processes. I'm posting this for anyone with a similar problem.
The htmldb_Get Javascript object is an oracle-apex wrapper for the XMLHttpRequest AJAX object. Poorly documented though.
I've found a copy of the code (at the bottom) and it turns out it has another function called GetAsync that allows to pass a function as a parameter to asign it to the onreadystatechange attribute on the XMLHttpRequest object, which will be executed each time the attribute readyState of the underlying XMLHttpRequest changes.
The function passed as a parameter can't have parameters on its own definition.
So, instead of calling get() on the htmldb_Get object you need to call GetAsync(someFunction)
With this solution in my case:
function something(){
var get;
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_1',0);
get.GetAsync(someFunctionStep1);
}
function someFunctionStep1(){
if(p.readyState == 0){ /*p is the underlying XMLHttpRequest object*/
console.log("request not initialized");
updateStatus('Running Step 1');
} else if(p.readyState == 1){
console.log("server connection established");
} else if(p.readyState == 2){
console.log("request received");
} else if(p.readyState == 3){
console.log("processing request");
} else if(p.readyState == 4){
console.log("request finished and response is ready");
callStep2();
}
}
function callStep2(){
var get;
get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=P6_STEP_2',0);
get.GetAsync(someFunctionStep2);
}
function someFunctionStep2(){
if(p.readyState == 0){
console.log("request not initialized");
updateStatus('Running Step 2');
} else if(p.readyState == 1){
console.log("server connection established");
} else if(p.readyState == 2){
console.log("request received");
} else if(p.readyState == 3){
console.log("processing request");
} else if(p.readyState == 4){
console.log("request finished and response is ready");
closeDialog();
}
}
Here's the htmldb_get definition, at the end is the GetAsync function
/*
str should be in the form of a valid f?p= syntax
*/
function htmldb_Get(obj,flow,req,page,instance,proc,queryString) {
//
// setup variables
//
this.obj = $x(obj); // object to put in the partial page
this.proc = proc != null ? proc : 'wwv_flow.show'; // proc to call
this.flow = flow != null ? flow : $x('pFlowId').value; // flowid
this.request = req != null ? req : ''; // request
this.page = page; // page
this.params = ''; // holder for params
this.response = ''; // holder for the response
this.base = null; // holder fot the base url
this.queryString = queryString!= null ? queryString : null ; // holder for passing in f? syntax
this.syncMode = false;
//
// declare methods
//
this.addParam = htmldb_Get_addParam;
this.add = htmldb_Get_addItem;
this.getPartial = htmldb_Get_trimPartialPage;
this.getFull = htmldb_Get_fullReturn;
this.get = htmldb_Get_getData;
this.url = htmldb_Get_getUrl;
this.escape = htmldb_Get_escape;
this.clear = htmldb_Get_clear;
this.sync = htmldb_Get_sync;
this.setNode = setNode;
this.replaceNode = replaceNode
//
// setup the base url
//
var u = window.location.href.indexOf("?") > 0 ?
window.location.href.substring(0,window.location.href.indexOf("?"))
: window.location.href;
this.base = u.substring(0,u.lastIndexOf("/"));
if ( this.proc == null || this.proc == "" )
this.proc = u.substring(u.lastIndexOf("/")+1);
this.base = this.base +"/" + this.proc;
//
// grab the instance form the page form
//
if ( instance == null || instance == "" ) {
var pageInstance = document.getElementById("pInstance");
if ( typeof(pageInstance) == 'object' ) {
this.instance = pageInstance.value;
}
} else {
this.instance = instance;
}
//
// finish setiing up the base url and params
//
if ( ! queryString ) {
this.addParam('p_request', this.request) ;
this.addParam('p_instance', this.instance);
this.addParam('p_flow_id', this.flow);
this.addParam('p_flow_step_id',this.page);
}
function setNode(id) {
this.node = html_GetElement(id);
}
function replaceNode(newNode){
var i=0;
for(i=this.node.childNodes.length-1;i>=0;i--){
this.node.removeChild(this.node.childNodes[i]);
}
this.node.appendChild(newNode);
}
}
function htmldb_Get_sync(s){
this.syncMode=s;
}
function htmldb_Get_clear(val){
this.addParam('p_clear_cache',val);
}
//
// return the queryString
//
function htmldb_Get_getUrl(){
return this.queryString == null ? this.base +'?'+ this.params : this.queryString;
}
function htmldb_Get_escape(val){
// force to be a string
val = val + "";
val = val.replace(/\%/g, "%25");
val = val.replace(/\+/g, "%2B");
val = val.replace(/\ /g, "%20");
val = val.replace(/\./g, "%2E");
val = val.replace(/\*/g, "%2A");
val = val.replace(/\?/g, "%3F");
val = val.replace(/\\/g, "%5C");
val = val.replace(/\//g, "%2F");
val = val.replace(/\>/g, "%3E");
val = val.replace(/\</g, "%3C");
val = val.replace(/\{/g, "%7B");
val = val.replace(/\}/g, "%7D");
val = val.replace(/\~/g, "%7E");
val = val.replace(/\[/g, "%5B");
val = val.replace(/\]/g, "%5D");
val = val.replace(/\`/g, "%60");
val = val.replace(/\;/g, "%3B");
val = val.replace(/\?/g, "%3F");
val = val.replace(/\#/g, "%40");
val = val.replace(/\&/g, "%26");
val = val.replace(/\#/g, "%23");
val = val.replace(/\|/g, "%7C");
val = val.replace(/\^/g, "%5E");
val = val.replace(/\:/g, "%3A");
val = val.replace(/\=/g, "%3D");
val = val.replace(/\$/g, "%24");
//val = val.replace(/\"/g, "%22");
return val;
}
//
// Simple function to add name/value pairs to the url
//
function htmldb_Get_addParam(name,val){
if ( this.params == '' )
this.params = name + '='+ ( val != null ? this.escape(val) : '' );
else
//this.params = this.params + '&'+ name + '='+ ( val != null ? val : '' );
this.params = this.params + '&'+ name + '='+ ( val != null ? this.escape(val) : '' );
return;
}
//
// Simple function to add name/value pairs to the url
//
function htmldb_Get_addItem(name,value){
this.addParam('p_arg_names',name);
this.addParam('p_arg_values',value);
}
//
// funtion strips out the PPR sections and returns that
//
function htmldb_Get_trimPartialPage(startTag,endTag,obj) {
setTimeout(html_processing,1);
if (obj) {this.obj = $x(obj);}
if (!startTag){startTag = '<!--START-->'};
if (!endTag){endTag = '<!--END-->'};
var start = this.response.indexOf(startTag);
var part;
if ( start >0 ) {
this.response = this.response.substring(start+startTag.length);
var end = this.response.indexOf(endTag);
this.response = this.response.substring(0,end);
}
if ( this.obj ) {
if(this.obj.nodeName == 'INPUT'){
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,100);
}else{
this.obj.value = this.response;
}
}else{
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,100);
}else{
this.obj.innerHTML = this.response;
}
}
}
//window.status = 'Done'
setTimeout(html_Doneprocessing,1);
return this.response;
}
var gResult = null;
var gNode = null
function htmldb_get_WriteResult(){
if(gNode && ( gNode.nodeName == 'INPUT' || gNode.nodeName == 'TEXTAREA')){
gNode.value = gResult;
}else{
gNode.innerHTML = gResult;
}
gResult = null;
gNode = null;
return;
}
//
// function return the full response
//
function htmldb_Get_fullReturn(obj) {
setTimeout(html_processing,1);
if (obj) { this.obj = html_GetElement(obj);}
if ( this.obj ) {
if(this.obj.nodeName == 'INPUT'){
this.obj.value = this.response;
}else{
if(document.all){
gResult = this.response;
gNode = this.obj;
var ie_HACK = 'htmldb_get_WriteResult()';
setTimeout(ie_HACK,10);
}else{
this.obj.innerHTML = this.response;
}
}
}
setTimeout(html_Doneprocessing,1);
return this.response;
}
//
// Perform the actual get from the server
//
function htmldb_Get_getData(mode,startTag,endTag){
html_processing();
var p;
try {
p = new XMLHttpRequest();
} catch (e) {
p = new ActiveXObject("Msxml2.XMLHTTP");
}
try {
var startTime = new Date();
p.open("POST", this.base, this.syncMode);
p.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
p.send(this.queryString == null ? this.params : this.queryString );
this.response = p.responseText;
if ( this.node )
this.replaceNode(p.responseXML);
if ( mode == null || mode =='PPR' ) {
return this.getPartial(startTag,endTag);
} if ( mode == "XML" ) {
setTimeout(html_Doneprocessing,1);
return p.responseXML;
} else {
return this.getFull();
}
} catch (e) {
setTimeout(html_Doneprocessing,1);
return;
}
}
function html_Doneprocessing(){
document.body.style.cursor="default";
}
function html_processing(){
document.body.style.cursor="wait";
}
/*
this adds better aysnc functionality
to the htmldb_Get object
pVar is the function that you want to call when the xmlhttp state changes
in the function specified by pVar the xmlhttp object can be referenced by the variable p
*/
htmldb_Get.prototype.GetAsync = function(pVar){
try{
p = new XMLHttpRequest();
}catch(e){
p = new ActiveXObject("Msxml2.XMLHTTP");
}
try {
var startTime = new Date();
p.open("POST", this.base, true);
if(p) {
p.onreadystatechange = pVar;
p.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
p.send(this.queryString == null ? this.params : this.queryString );
return p;
}
}catch(e){
return false;
}
}
/* PDF OUTPUT */
/*Gets PDF src XML */
function htmldb_ExternalPost(pThis,pRegion,pPostUrl){
var pURL = 'f?p='+html_GetElement('pFlowId').value+':'+html_GetElement('pFlowStepId').value+':'+html_GetElement('pInstance').value+':FLOW_FOP_OUTPUT_R'+pRegion
document.body.innerHTML = document.body.innerHTML + '<div style="display:none;" id="dbaseSecondForm"><form id="xmlFormPost" action="' + pPostUrl + '?ie=.pdf" method="post" target="pdf"><textarea name="vXML" id="vXML" style="width:500px;height:500px;"></textarea></form></div>';
var l_El = html_GetElement('vXML');
var get = new htmldb_Get(l_El,null,null,null,null,'f',pURL.substring(2));
get.get();
get = null;
setTimeout('html_GetElement("xmlFormPost").submit()',10);
return;
}
function $xml_Control(pThis){
this.xsl_string = '<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="html"/><xsl:param name="xpath" /><xsl:template match="/"><xsl:copy-of select="//*[#id=$xpath]"/></xsl:template></xsl:stylesheet>';
if(document.all){
this.xsl_object = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
this.xsl_object.async=false;
this.xsl_object.loadXML(this.xsl_string)
tmp = new ActiveXObject("Msxml2.XSLTemplate.3.0");
tmp.stylesheet = this.xsl_object;
this.xsl_processor = tmp.createProcessor();
}else{
this.xsl_object = (new DOMParser()).parseFromString(this.xsl_string, "text/xml");
this.xsl_processor = (new XSLTProcessor());
this.xsl_processor.importStylesheet(this.xsl_object);
this.ownerDocument = document.implementation.createDocument("", "test", null);
}
this.xml = pThis;
this.CloneAndPlace = _CloneAndPlace;
return
function _CloneAndPlace(pThis,pThat,pText){
var lThat = $x(pThat);
if(document.all){
this.xsl_processor.addParameter("xpath", pThis);
this.xsl_processor.input = this.xml;
this.xsl_processor.transform;
var newFragment = this.xsl_processor.output;
}else{
this.xsl_processor.setParameter(null, "xpath", pThis);
var newFragment = this.xsl_processor.transformToFragment(this.xml,this.ownerDocument);
}
if(lThat){
if(document.all){
lThat.innerHTML='';
lThat.innerHTML=newFragment;
}else{
lThat.innerHTML='';
lThat.appendChild(newFragment);
}
/*
in IE newFragment will be a string
in FF newFragment will be a dome Node (more useful)
*/
return newFragment;
}
}
}

Categories

Resources