Updating multiple records in XML using Javascript - javascript

Heading
Hi, I have a lambda running javascript that uses an api to create and update records from one system and into another.
It works but takes a while because the dml statement is in a loop. I really need to iterate over the array and create one instance of the object to update, but am not very familiar with xml.
Based on documentation here is the format I need for multiple records:
<update>
<technician>
<id>1355196</id>
<name>Jim Smith</name>
<business_unit>Plumbing Service</business_unit>
</technician>
<technician>
<id>1355200</id>
<name>John Doe</name>
<business_unit>HVAC Sales</business_unit>
</technician>
</update>
Right now this is format I have, updating one at a time:
1st update call:
<update>
<technician>
<id>1355196</id>
<name>Jim Smith</name>
<business_unit>Plumbing Service</business_unit>
</technician>
</update>
2nd update call:
<update>
<technician>
<id>1355200</id>
<name>John Doe</name>
<business_unit>HVAC Sales</business_unit>
</technician>
</update>
And so on...
Here is the code I have now, one record at a time:
async function updateTechnicians(location, itechs, stechs) {
let logger = bootstrap.logger();
try {
const client = bootstrap.client(logger);
let sTechMap = new Map();
for(const tech in stechs){
sTechMap.set(parseInt(stechs[tech].id).toString(), stechs[tech])
}
for(const tech in itechs){
if(itechs[tech].location == location){
let thisTech = sTechMap.get(itechs[tech].servicetitanid)
let update = new UpdateTechnician();
if(thisTech){
update.id = itechs[tech].id;
update.name = thisTech.name;
update.database_active = thisTech.active;
if(thisTech.businessUnit != null){
update.tenant = thisTech.businessUnit.tenant.name;
update.business_unit = thisTech.businessUnit.name;
if(thisTech.businessUnit.name.includes('Phx')){ update.branch = 'Phoenix'; }
else if(thisTech.businessUnit.name.includes('Tuc')){ update.branch = 'Tucson'; }
else if(thisTech.businessUnit.name.includes('Simi')){ update.branch = 'Simi Valley'; }
else if(location == 'NV'){ update.branch = 'Las Vegas'; }
else if(location == 'CA'){ update.branch = 'Corona'; }
}
if(itechs[tech].deactivatedOn != ''){
update.deactivatedOn == '';
}
const response = await client.execute(update);
const result = response.getResult();
}
else{
let today = new Date();
let date = (today.getMonth()+1)+'/'+today.getDate()+'/'+today.getFullYear();
update.id = itechs[tech].id;
update.name = itechs[tech].name;
update.database_active = false;
if(itechs[tech].deactivatedOn == null){
update.deactivatedOn = date;
}
const response = await client.execute(update);
const result = response.getResult();
}
}
}
} catch (ex) {
if (ex instanceof IA.Exceptions.ResponseException) {
logger.error("A server response exception was thrown", {
"Class": ex.constructor.name,
"Message": ex.message,
"API Errors": ex.errors,
});
console.log("Failed! " + ex.message);
} else {
logger.error("An exception was thrown", {
"Class": ex.constructor.name,
"Message": ex.message,
});
console.log(ex.name)
}
}
}
class AbstractObject extends IA.Functions.AbstractFunction {
constructor(controlId) {
super(controlId);
this.integrationName = 'technician';
}
}
class UpdateTechnician extends AbstractObject {
constructor(controlId) {
super(controlId);
}
writeXml(xml) {
xml.writeStartElement("function");
xml.writeAttribute("controlid", this.controlId, true);
xml.writeStartElement("update");
xml.writeStartElement(this.integrationName);
xml.writeElement("id", this.id);
xml.writeElement("name", this.name);
xml.writeElement("business_unit", this.business_unit);
xml.writeElement("branch", this.branch);
xml.writeElement("tenant", this.tenant);
xml.writeElement("location", this.location);
xml.writeElement("database_active", this.database_active);
xml.writeElement("deactivated_on", this.deactivatedOn);
xml.writeEndElement(); // test_object
xml.writeEndElement(); // create
xml.writeEndElement(); // function
}
}

I got some help from a developer friend. Here is code:
async function updateTechnicians(location, itechs, stechs) {
let logger = bootstrap.logger();
try {
const client = bootstrap.client(logger);
let sTechMap = new Map();
for (const tech in stechs) {
sTechMap.set(stechs[tech].id.toString(), stechs[tech]);
}
let update = new UpdateTechnician();
for (const tech in itechs) {
if (itechs[tech].location == location) {
let thisTech = sTechMap.get(itechs[tech].servicetitanid);
let updateItem = {};
if (thisTech) {
updateItem.id = itechs[tech].id;
updateItem.name = thisTech.name;
updateItem.database_active = thisTech.active;
if (thisTech.businessUnit != null) {
updateItem.tenant = thisTech.businessUnit.tenant.name;
updateItem.business_unit = thisTech.businessUnit.name;
if (thisTech.businessUnit.name.includes('Phx')) {
updateItem.branch = 'Phoenix';
} else if (thisTech.businessUnit.name.includes('Tuc')) {
updateItem.branch = 'Tucson';
} else if (thisTech.businessUnit.name.includes('Simi')) {
updateItem.branch = 'Simi Valley';
} else if (location == 'NV') {
updateItem.branch = 'Las Vegas';
} else if (location == 'CA') {
updateItem.branch = 'Corona';
}
}
if (itechs[tech].deactivatedOn != null) {
updateItem.deactivatedOn == null;
}
update.arrUpdate.push(updateItem);
} else {
let today = new Date();
let date = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
updateItem.id = itechs[tech].id;
updateItem.name = itechs[tech].name;
updateItem.database_active = false;
if (itechs[tech].deactivatedOn == null) {
updateItem.deactivatedOn = date;
}
update.arrUpdate.push(updateItem);
}
}
}
const response = await client.execute(update);
const result = response.getResult();
// console.log(result);
} catch (ex) {
if (ex instanceof IA.Exceptions.ResponseException) {
logger.error("A server response exception was thrown", {
"Class": ex.constructor.name,
"Message": ex.message,
"API Errors": ex.errors,
});
console.log("Failed! " + ex.message);
} else {
logger.error("An exception was thrown", {
"Class": ex.constructor.name,
"Message": ex.message,
});
console.log(ex.name);
}
}
}
class AbstractObject extends IA.Functions.AbstractFunction {
constructor(controlId) {
super(controlId);
this.integrationName = 'technician';
}
}
class UpdateTechnician extends AbstractObject {
constructor(controlId) {
super(controlId);
this.arrUpdate = [];
}
writeXml(xml) {
//console.log(this.arrUpdate);
xml.writeStartElement("function");
xml.writeAttribute("controlid", this.controlId, true);
xml.writeStartElement("update");
for (const i in this.arrUpdate) {
const item = this.arrUpdate[i];
xml.writeStartElement("technician");
xml.writeElement("id", item.id);
xml.writeElement("name", item.name);
xml.writeElement("business_unit", item.business_unit);
xml.writeElement("branch", item.branch);
xml.writeElement("tenant", item.tenant);
xml.writeElement("location", item.location);
xml.writeElement("database_active", item.database_active);
xml.writeElement("deactivated_on", item.deactivatedOn);
xml.writeEndElement();
}
xml.writeEndElement(); // create
xml.writeEndElement(); // function
}
}

Related

Async call in javascript For Loop not working

I have a callback function inside a loop here for (var res in results) {
but it seems the loop is not waiting for the async call. When I am calling self.callTestOutputData(test_output_url) here, the loop is not waiting fpor the response but continuing for the next iteration and I am losing out the value to push into obj.requistion_number = testOutputResponse.value;
Please note : var results = response.results Here results is an array of Json objects.
Edit 1 : I tried forEach but that didn't work .
results.forEach(res => {
var obj = {}
obj.ferp = res.name;
// your code...
})
Original Code:
self.downloadDailyExcelProcurement = function (filters, excelTmpArr) {
self.disableExcelDownloadProcurement(true);
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label')[0].style.backgroundColor = "gray";
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label .demo-download-icon-24')[0].style.color = "#D8D8D8";
var payload = {};
if (typeof filters === "string") {
var fill = filters;
} else {
var fill = self.sendFilters();
if(self.app() === "fusion"){
fill += '&module=Procurement';
}else if (self.app() === "o2r"){
fill += '&module=O2r';
}
}
if(fill.includes("%3A")){
fill = fill.replace(/%3A/g, ':');
}
payload.Endpoint = 'executions/testcollection/' + fill;
//console.log(payload.Endpoint)
payload.BeforeSend = function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('guest:oracle123'));
$(".custom-loader-circle").show();
};
payload.OnSuccess = function (response) {
var results = response.results;
for (var res in results) {
var obj = {}
obj.ferp = results[res].name;
obj.po = "NA"
obj.receipt_no = "NA"
var test_output_url = results[res].reference_test_cases[0].automation_tests[0].test_outputs[0]
$.when(self.callTestOutputData(test_output_url)).done(function (testOutputResponse) {
if(testOutputResponse)
obj.requistion_number = testOutputResponse.value;
else {
obj.requistion_number = "NA";
}
self.excelTmpArr().push(obj);
});
}
else {
self.excelTmpArr().push(obj);
}
}
if (response.next) {
filters = ((response.next).split('testcollection'))[1];
if (filters[0] === "/") {
var test = filters.slice(1, filters.length);
}
self.downloadDailyExcelProcurement(test, self.excelTmpArr());
} else {
if (results.length === 0) {
$(".custom-loader-circle").hide();
self.disableExcelDownloadProcurement(false);
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label')[0].style.backgroundColor = "#4d0000";
$('.useCaseExcelButtonProcurement .oj-button-button .oj-button-label .demo-download-icon-24')[0].style.color = "white";
showMessage(self.messages, "No Data to Download", '', 'info');
} else {
self.formatForExcel(self.excelTmpArr(), fill, "Procurement");
}
}
};
payload.OnError = function (data) {
showMessage(self.messages, data.status, data.statusText, 'error');
$(".custom-loader-circle").hide();
};
getData(payload);
}
Try using async and await :
async function asyncCall () {
// call here
}
for (var res in results) {
const response = await asyncCall();
}
var results = response.results;
if(result.length > 0){
results.map((data,index)=>{
//write your code here
})
}
This will help you ..
Use forEach() to iterate since it creates its own function closure:
results.forEach(res => {
var obj = {}
obj.ferp = res.name;
// your code...
})

For loops breaks when using await

I have a problem when using await in a for loop. Every time it hits the await funtion it executes it fine, but it stops loping through the rest of the array that is looping through. I'm using nodejs with axios to send http request to a restAPI. The function that is in the api is big. So I thought maby that is the problem but it wasn't. Also the api uses its own await functions to, but that wasn't the problem either(As far as I know).
Here is my code for the request
var files = await globPromise("assets/series/**/*.json");
var json = null;
var file = null;
var series = [];
for (i = 0; i < files.length; i++) {
file = files[i];
var raw = fs.readFileSync(file);
json = JSON.parse(raw);
if (json.type === "series") {
try {
var userId = null;
if (req.user == null) {
userId = req.query.userid;
} else {
userId = req.user.id;
}
const response = await axios.get("http://" + host + "/series/info/" + json.id + "?userid=" + userId);
series.push(JSON.parse(response.data));
} catch (error) {
console.log(error);
series.push(json);
}
}
}
res.json(JSON.stringify(series));
});
And also the api side:
app.get('/series/info/:id', async(req, res) => {
var files = await globPromise("assets/series/**/*.json");
var json = null;
var file = null;
for (i = 0; i < files.length; i++) {
file = files[i];
var raw = fs.readFileSync(file);
json = JSON.parse(raw);
if (json.type === "series" && json.id === req.params.id) {
break;
}
json = null;
}
let path = pathFs.dirname(file) + "/";
try {
var seriesFiles = await fsPromise.readdir(path);
var latestWatchedVideo = null;
var latestWatchedTime = null;
var latestWatchTime = null;
var latestWatchDuration = null;
var seasonCount = 0;
var seasons = [];
for (i = 0; i < seriesFiles.length; i++) {
seriesFile = seriesFiles[i];
if (fs.lstatSync(path + "/" + seriesFile).isDirectory()) {
if (!seriesFile.startsWith("s")) {
continue;
}
seasonCount++;
try {
var videoFiles = await fsPromise.readdir(path + "/" + seriesFile + "/");
var videos = [];
for (let i = 0; i < videoFiles.length; i++) {
const video = videoFiles[i];
if (video.endsWith(".json")) {
var rawVideo = fs.readFileSync(path + "/" + seriesFile + "/" + video);
videoJson = JSON.parse(rawVideo);
const query = util.promisify(con.query).bind(con);
var userId = null;
if (req.user == null) {
userId = req.query.userid;
} else {
userId = req.user.id;
}
var results = await query(`SELECT * FROM watched WHERE video_id = "${videoJson.id}" AND user_id = "${userId}"`);
if (results.length > 0) {
var updated = JSON.parse(JSON.stringify(results[0].updated));
var duration = JSON.parse(JSON.stringify(results[0].duration));
var time = JSON.parse(JSON.stringify(results[0].time));
if (latestWatchedVideo == null) {
latestWatchedVideo = videoJson.id;
latestWatchedTime = updated;
latestWatchTime = time;
latestWatchDuration = duration;
} else {
if (latestWatchedTime < updated) {
latestWatchedVideo = videoJson.id;
latestWatchedTime = updated;
latestWatchTime = time;
latestWatchDuration = duration;
}
}
}
videos.push(videoJson);
}
}
function compare(a, b) {
if (a.episode < b.episode) {
return -1;
}
if (a.episode > b.episode) {
return 1;
}
return 0;
}
videos.sort(compare);
seasons.push({
season: seasonCount,
title: seriesFile.replace("s" + seasonCount, ""),
videos: videos
});
} catch (error) {
console.log(error);
}
}
}
json.seasonCount = seasonCount;
json.seasons = seasons;
json.latestWatchDuration = latestWatchDuration;
json.latestWatchTime = latestWatchTime;
json.latestWatchedVideo = latestWatchedVideo;
json.latestWatchedTime = latestWatchedTime;
res.json(JSON.stringify(json));
} catch (error) {
console.log(error);
}
});
Is there something (important) about await and async that I've missed?
Edit: my problem is that is loops fine through the first item and the await is working fine too, but it stops the loop and executes the next lines of code like there are no other items in my array.
Solved: I tried using the for/of and it works now. I don't know whats is so different between de default for and this one but it works!

JavaScript GetLocalResourceObject from .resx file

I'm trying to get the local ressources key from .rsex file in javascript, but it doesn't work, I got error "not available".
Thanks for your help.
var key = "errMesgLength"
var val = eval('<%= GetLocalResourceObject("' + key + '") %>');
lblMessage.innerHTML = val;
Thank you Michael for help.
I have found a solution.
In C# code I have used a web method
[WebMethod()]
public static string GetLocalRessources(string key)
{
var currentLanguage = (Language)HttpContext.Current.Session["CurrentLanguage"];
if (currentLanguage == Language.French)
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-FR");
}
else
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
return HttpContext.GetLocalResourceObject("~/SelfRegistration.aspx", key, Thread.CurrentThread.CurrentCulture).ToString();
}
and in JS code, I have used PageMethos call
function IsIMEI() {
var imei = document.querySelector(".txt-imei");
var lblMessage = document.querySelector(".lblMsgError");
var key;
if (imei) {
if (imei.value !== "IMEI / Serial Number") {
if (imei.value.toString().length > 7) {
imei.style.border = "";
lblMessage.innerHTML = "";
return true;
}
else {
key = "errMesgLength"
PageMethods.GetLocalRessources(key, onSucess, onError);
return false;
}
}
else {
imei.style.border = "1px solid red";
key = "errMesgIMEI"
PageMethods.GetLocalRessources(key, onSucess, onError);
return false;
}
}
}
function onSucess(result) {
var lblMessage = document.querySelector(".lblMsgError");
lblMessage.innerHTML = result;
}
function onError(error) {
alert(error._message);
}

NodeJs Proxy Connection

why I cant connect with username and password with SOCKS5 like
username:password#ip:port, i can with HTTP, but cant with SOCKS5
doneusername:password#ip:port, i can with HTTP, but cant with SOCKS5
done
SOCKS5 ; username:password#ip:port
Attempting connection to ws://ip:port
Connecting to: ws://ip:port
net.js:928
throw new RangeError('port should be >= 0 and < 65536: ' + port);
^
RangeError: port should be >= 0 and < 65536: NaN
at lookupAndConnect (net.js:928:13)
at Socket.connect (net.js:905:5)
at Socket.connect (net.js:868:37)
var WebSocket = require('ws');
var valid_player_pos = null;
var reconnect = false;
var suicide_targets = null;
var socket = require('socket.io-client')(config.feederServer);
socket.on('pos', function(data) {
valid_player_pos = data;
//console.log(data);
});
socket.on('cmd', function(data) {
console.log(data);
if (data.name == "split") {
for (bot in bots) {
bots[bot].client.split();
}
} else if (data.name == "eject") {
for (bot in bots) {
bots[bot].client.eject();
}
} else if (data.name == "connect_server") {
if (data.ip == null) {
return;
}
if (data.ip == "") {
return;
}
for (bot in bots) {
bots[bot].client.disconnect();
}
bots = {};
game_server_ip = data.ip;
console.log("client requested bots on: " + game_server_ip);
setTimeout(function() {
startFeederBotOnProxies();
}, 1000);
} else if(data.name == "reconnect_server") {
reconnect = true;
if (data.ip == null) {
return;
}
if (data.ip == "") {
return;
}
for (bot in bots) {
bots[bot].client.disconnect();
}
bots = {};
game_server_ip = data.ip;
console.log("client requested bots on: " + game_server_ip);
}
});
socket.on('force-login', function(data) {
console.log(data);
if (data == "server-booted-up") {
return;
}
socket.emit("login", {
"uuid": config.client_uuid,
"type": "server"
});
});
fs = require('fs');
var HttpsProxyAgent = require('https-proxy-agent');
var Socks = require('socks');
function getRandomLine(filename) {
var fs = require('fs');
var lines = fs.readFileSync(filename).toString().split("\n");
line = lines[Math.floor(Math.random() * lines.length)];
return line
}
//object of bots
var bots = {};
bot_count = 0;
var fs = require('fs');
var lines = fs.readFileSync(config.proxies).toString().split("\n");
var url = require('url');
var game_server_ip = null;
function createAgent(ip,type) {
data = ip.split(":");
return new Socks.Agent({
proxy: {
ipaddress: data[0],
port: parseInt(data[1]),
type: parseInt(type)
}}
);
}
var proxy_mode = "HTTP";
function startFeederBotOnProxies() {
for (proxy_line in lines) {
if(lines[proxy_line].trim() == "#HTTP"){
proxy_mode = "HTTP";
}else if(lines[proxy_line].trim() == "#SOCKS4"){
proxy_mode = "SOCKS4";
}else if(lines[proxy_line].trim() == "#SOCKS5"){
proxy_mode = "SOCKS5";
}
if (lines[proxy_line][0] == "#" || lines[proxy_line].length < 3) {
continue;
}
//usefull for testing single proxies
if (process.argv[3] != null && proxy_line != process.argv[3]) {
continue;
}
proxy = "http://" + lines[proxy_line];
proxy_single = lines[proxy_line];
console.log(proxy_mode + " ; " + proxy_single);
try {
var opts = url.parse(proxy);
if (proxy != null) {
if(proxy_mode=="HTTP"){
agent = HttpsProxyAgent(opts);
}else if(proxy_mode=="SOCKS4"){
agent = createAgent(lines[proxy_line],4);
}else if(proxy_mode=="SOCKS5"){
agent = createAgent(lines[proxy_line],5);
}
} else {
var agent = null;
}
if (lines[proxy_line] == "NOPROXY") {
agent = null;
}
console.log("Attempting connection to " + game_server_ip);
for (i = 0; i < config.botsPerIp; i++) {
if(bot_count<config.maxBots){
bot_count++;
bots[bot_count] = new FeederBot(bot_count, agent, bot_count, game_server_ip);
}
}
} catch (e) {
console.log('Error occured on startup: ' + e);
}
}
}
console.log("ogar-feeder-bot started! Join a game in Chrome with the Userscript installed.");
console.log("Press CTRL + C to stop this script.");
From all of discussions I get that the problem with Your createAgent.
So use this code and be happy (:
function createAgent(connectionString, type) {
var type = parseInt(type || 5);
var ipParts = connectionString.split('#'); // splitting user:pass#host:port
var host, port, username, password;
switch(ipParts.length) {
case 3 : // somebody#somewhere.com:somepassword#proxy.com:1080
var credentials = (ipParts[0]+'#'+ipParts[1]).split(':'); // yusolokuji#leeching.net:luquitas
username = credentials[0]; // somebody#somewhere.com
password = credentials[1]; // somepassword
var hostParts = ipParts[2].split(':'); // proxy.com:1080
host = hostParts[0];
port = hostParts[1] || 1080;
break;
case 2 : // somebody:somepassword#proxy.com:1080
var credentials = ipParts[0].split(':'); // somebody:somepassword
username = credentials[0]; // somebody
password = credentials[1]; // somepassword
var hostParts = ipParts[1].split(':'); // proxy.com:1080
host = hostParts[0];
port = hostParts[1] || 1080;
break;
case 1 : // proxy.com:1080
ipParts = ipParts[0].split(':');
host = ipParts[0];
port = ipParts[1];
break;
}
var config = {
proxy: {
ipaddress: host,
port: parseInt(port),
type: type
}
};
if(type == 5) {
config.proxy.authentication = {
username: username,
password: password
};
}
if(type == 4) {
config.proxy.user_id = username;
}
return new Socks.Agent(config);
}

Uncaught TypeError: Cannot read property 'options' of null

I cannot figure out why I keep getting this error:
Uncaught TypeError: Cannot read property 'options' of null
getFSREPlist
(anonymous function)
The error is referencing this line of code (21):
document.getElementById(elementidupdate).options.length=0;
What is weird is that it was working prior to this new google map api I just put on. Also, it is pulling the country code "1" and putting it in the drop down, but not the province code "19".
Here is the on page script:
getFSREPlist('1', 'fsrep-search-province', 'CountryID', '19');getFSREPlist('19', 'fsrep-search-city', 'ProvinceID', '3'); request.send(null);
Here is the full file:
function sack(file) {
this.xmlhttp = null;
this.resetData = function () {
this.method = "POST";
this.queryStringSeparator = "?";
this.argumentSeparator = "&";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;
this.element = null;
this.elementObj = null;
this.requestFile = file;
this.vars = new Object();
this.responseStatus = new Array(2);
};
this.resetFunctions = function () {
this.onLoading = function () {};
this.onLoaded = function () {};
this.onInteractive = function () {};
this.onCompletion = function () {};
this.onError = function () {};
this.onFail = function () {};
};
this.reset = function () {
this.resetFunctions();
this.resetData();
};
this.createAJAX = function () {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
if (!this.xmlhttp) {
if (typeof XMLHttpRequest != "undefined") {
this.xmlhttp = new XMLHttpRequest();
} else {
this.failed = true;
}
}
};
this.setVar = function (name, value) {
this.vars[name] = Array(value, false);
};
this.encVar = function (name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
}
}
this.processURLString = function (string, encode) {
encoded = encodeURIComponent(this.argumentSeparator);
regexp = new RegExp(this.argumentSeparator + "|" + encoded);
varArray = string.split(regexp);
for (i = 0; i < varArray.length; i++) {
urlVars = varArray[i].split("=");
if (true == encode) {
this.encVar(urlVars[0], urlVars[1]);
} else {
this.setVar(urlVars[0], urlVars[1]);
}
}
}
this.createURLString = function (urlstring) {
if (this.encodeURIString && this.URLString.length) {
this.processURLString(this.URLString, true);
}
if (urlstring) {
if (this.URLString.length) {
this.URLString += this.argumentSeparator + urlstring;
} else {
this.URLString = urlstring;
}
}
this.setVar("rndval", new Date().getTime());
urlstringtemp = new Array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeURIString) {
encoded = this.encVar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = Array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
if (urlstring) {
this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
} else {
this.URLString += urlstringtemp.join(this.argumentSeparator);
}
}
this.runResponse = function () {
eval(this.response);
}
this.runAJAX = function (urlstring) {
if (this.failed) {
this.onFail();
} else {
this.createURLString(urlstring);
if (this.element) {
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "GET") {
totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
try {
this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
} catch (e) {}
}
this.xmlhttp.onreadystatechange = function () {
switch (self.xmlhttp.readyState) {
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
if (self.execute) {
self.runResponse();
}
if (self.elementObj) {
elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
if (self.responseStatus[0] == "200") {
self.onCompletion();
} else {
self.onError();
}
self.URLString = "";
break;
}
};
this.xmlhttp.send(this.URLString);
}
}
};
this.reset();
this.createAJAX();
}
var ajax = new Array();
function getFSREPlist(sel, elementidupdate, fsrepvariable, currentvalue) {
if (sel == '[object]' || sel == '[object HTMLSelectElement]') {
var FSREPID = sel.options[sel.selectedIndex].value;
} else {
var FSREPID = sel;
}
document.getElementById(elementidupdate).options.length = 0;
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'http://www.cabcot.com/wp-content/plugins/firestorm-real-estate-plugin/search.php?' + fsrepvariable + '=' + FSREPID + '&cvalue=' + currentvalue;
ajax[index].onCompletion = function () {
ElementUpdate(index, elementidupdate)
};
ajax[index].runAJAX();
}
function ElementUpdate(index, elementidupdate) {
var obj = document.getElementById(elementidupdate);
eval(ajax[index].response);
}
You should call getFSREPlist when DOM is loaded. I ran
document.getElementById('fsrep-search-province').options.length=0
from chrome´s console. while page was still loading and caused that same error.
http://i.imgur.com/GBFizq1.png

Categories