Adding javascript loops into SQL database - javascript

What i am trying to achieve is adding the javascript loops and the named variables into an sql database, some of them are already added to an external script so work fine however some which i have named in the SQL script at the bottom still need adding, however as the database won't accept a colon ":" they won't enter it and is returning an error, looking at the code at the bottom with replace function im sure you can see what i am trying to achieve but failing miserably, help is much appreciated!
window.status = 'Loading contingency scripts - please wait...';
audit('Loading contingency scripts');
var conting = {
i: 0,
start: function() {
window.status = 'Loading form - please wait...';
var t = '';
t += '<form name="frm_conting" id="frm_conting" onsubmit="return false;">';
t += '<table width="100%" cellspacing="1" cellpadding="0">';
t += '<tr><td>Date (DD/MM/YY):</td><td><input type="text" size="8" value="' + current_date + '" id="date"></td></tr>';
t += '<tr><td>Time Started:</td><td><select id="timefrom"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select></td></tr>';
t += '<tr><td>Time Finished:</td><td><select id="timeto"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select><tr><td>Extension #:</td><td><input type="text" size="5" value="' + my.extension + '" id="staffid"></td></tr>';
t += '<tr><td>Desk ID:</td><td><input type="text" size="5" value=' + my.deskid + ' id="desk"></td></tr>';
t += '<tr><td>Number of calls:</td><td><input type="text" size="5" id="calls"></td></tr>';
t += '<tr><td>Avid ID:</td><td><input type="text" size="5" id="avid"></td></tr>';
t += '<tr><td><input type="button" value="Submit" onClick="conting.save()"></td>';
t += '</table>';
t += '</form>';
div_form.innerHTML = t;
window.resizeTo(400, 385);
window.status = '';
},
save: function() {
var conting_date = frm_conting.date.value;
if (!isdate(conting_date)) {
alert("You have entered an incorrect date.");
return false;
};
var conting_timefrom = frm_conting.timefrom.value;
var conting_timeto = frm_conting.timeto.value;
if (conting_timefrom == '' || conting_timeto == '') {
alert("You need to enter a starting & finishing time.");
return false;
};
if (conting_timefrom > conting_timeto) {
alert("The time you have entered is after the finish time.");
return false;
};
var conting_staffid = frm_conting.staffid.value;
if (conting_staffid.length != 5) {
alert("You have entered an incorrect extension number.");
return false;
};
var conting_desk = frm_conting.desk.value;
if (conting_desk.length != 5) {
alert("You have entered an incorrect desk ID.");
return false;
};
var conting_calls = frm_conting.calls.value;
if (isNaN(conting_calls)) {
alert("You have not entered amount of calls.");
return false;
};
var conting_avid = frm_conting.avid.value;
if (isNaN(conting_avid)) {
alert("You have entered an incorrect avid ID.");
return false;
};
if (conting_avid.length != 5) {
alert("You have entered an incorrect avid ID.");
return false;
};
conn.open(db["contingency"]);
rs.open("SELECT MAX(prac_id) FROM practice", conn);
var prac_id = rs.fields(0).value + 1;
var prac_timefrom = parseFloat(frm_conting.timefrom.value);
var prac_timeto = parseFloat(frm_conting.timefrom.value);
var prac_calls = frm_conting.calls.value;
var prac_avid = frm_conting.avid.value;
rs.close();
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
conn.close();
}
};
window.status = '';​

This bit of code looks extremely dubious.
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
you should use parameterised queries to avoid SQL injection. Additionally even without any deliberate SQL injection attempts this code will fail if any of the form fields contain the ' character.
You are assigning to the variable q twice and aren't executing the result of the first assignment. (And declaring it twice actually?!)
There is no syntax such as UPDATE SELECT it would need to be something like UPDATE practice SET SomeColumn = REPLACE (SomeColumn, 'isNaN', 'isNull') presumably except see 4 and 5.
I'm not clear what the Replace is meant to be doing anyway. What are the 3 parameters you have given it?
It would be better to do the Replace on the value before inserting into the database rather than inserting it wrong then updating it to the new value.

Related

JavaScript Syntax error

I have two functions in JavaScript and get the following error:
Uncaught SyntaxError: missing ) after argument list
It is not giving me a line number and I can't seem to find the culprit; would appreciate any assistance:
function makeRequest() {
var xmlhttp = new XMLHttpRequest();
console.log('reached');
xmlhttp.onreadystatechange = function() //This part is actually executed last
{
console.log("within");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) // Was the request processed successfully?
{
console.log(location);
console.log(xmlhttp.responseText);
first = xmlhttp.responseText.substring(xmlhttp.responseText
.search('first:') + 6, xmlhttp.responseText
.search(',last'));
console.log("First: " + first);
last = xmlhttp.responseText.substring(xmlhttp.responseText
.search(',last') + 6, xmlhttp.responseText
.search(',utt'));
console.log("last: " + last);
utt = xmlhttp.responseText.substring(xmlhttp.responseText
.search(',utt') + 5, xmlhttp.responseText
.search(',type'));
console.log("utt: " + utt);
type = "";
attribute = "";
out = "";
index = "";
values = "";
if (xmlhttp.responseText.search(',att') > -1) {
type = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',type') + 6,
xmlhttp.responseText.search(',att'));
//attribute
pass = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',att') + 5,
xmlhttp.responseText.search(',vals'));
values = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',vals') + 7,
xmlhttp.responseText.search(']}'));
} else {
type = 'instance';
//index
pass = xmlhttp.responseText
.substring(xmlhttp.responseText
.search('indexResult:') + 12,
xmlhttp.responseText.search(',inst:'));
out = xmlhttp.responseText.substring(
xmlhttp.responseText.search('inst:') + 5,
xmlhttp.responseText.search('}'));
}
console.log("type: " + type);
if (type === 'attribute') {
vals = values.split(",");
html = "You have said the following to the virtual assistant: </br><i>'"
+ utt
+ "'</i></br></br>Given that you have said this; what would be your preferred "
+ attribute.toLowerCase().substring(0,
attribute.length - 1)
+ "&#63</br></br><select id='choice' name='attribute'><option selected='selected' value='makeSelection'>please choose</option>";
for (i = 0; i < vals.length; i++) {
html = html + "<option value='"+vals[i]+"'>"
+ vals[i] + "</option>";
}
html = html
+ "</select></br></br><input type='button' onclick='return sendChoice("
+ first + "," + last + "," + utt + "," + type
+ "," + pass + ")' value='Submit'></input>";
document.getElementById("utteranceDiv").innerHTML = html;
}
if (type === 'instance') {
html = "You have said the following to the virtual assistant: </br><i>'"
+ utt
+ "'</i></br></br>Given that you have said this; </br> "
+ out
+ "</br><select id='choice' name='attribute'><option selected='selected' value='makeSelection'>please choose</option><option value='yes'>yes</option><option value='no'>no</option></select></br></br><input type='button' onclick='return sendChoice("
+ first
+ ","
+ last
+ ","
+ utt
+ ","
+ type
+ "," + pass + ")' value='Submit'></input>";
document.getElementById("utteranceDiv").innerHTML = html;
}
}
}
console
.log("http://"
+ server
+ "/DialogueRefinementWebExperiment/WebExperimentServlet?first="
+ first + "&last=" + last);
xmlhttp
.open(
"Get",
"http://"
+ server
+ "/DialogueRefinementWebExperiment/WebExperimentServlet?first="
+ first + "&last=" + last, true);
console.log('before');
xmlhttp.send();
console.log('after');
}
and the other function is:
function sendChoice(fname, lname, utterance, type, pass) {
if (document.getElementById('choice').value === 'makeSelection') {
alert('please make a choice');
return false;
}
else {
choice = document.getElementById('choice').value;
first = fname;
last = lname;
utt = utterance;
typ = type;
attOrInstIndex = pass;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() //This part is actually executed last
{
console.log("within");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) // Was the request processed successfully?
{
console.log(location);
console.log(xmlhttp.responseText);
type = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',type') + 6,
xmlhttp.responseText.search(',att'));
attribute = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',att') + 5,
xmlhttp.responseText.search(',vals'));
values = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',vals') + 7,
xmlhttp.responseText.search(']}'));
vals = values.split(",");
console.log("type: " + type);
if (xmlhttp.responseText.search(',att') > -1) {
type = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',type') + 6,
xmlhttp.responseText.search(',att'));
//attribute
pass = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',att') + 5,
xmlhttp.responseText.search(',vals'));
values = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',vals') + 7,
xmlhttp.responseText.search(']}'));
} else if (xmlhttp.responseText.search('instance') > -1) {
type = 'instance';
//index
pass = xmlhttp.responseText
.substring(xmlhttp.responseText
.search('indexResult:') + 12,
xmlhttp.responseText
.search(',inst:'));
out = xmlhttp.responseText.substring(
xmlhttp.responseText.search('inst:') + 5,
xmlhttp.responseText.search('}'));
} else {
type = 'done';
}
if (type === 'attribute') {
vals = values.split(",");
html = "You have said the following to the virtual assistant: </br><i>'"
+ utt
+ "'</i></br></br>Given that you have said this and the choices you have made so far; what would be your preferred "
+ attribute.toLowerCase().substring(0,
attribute.length - 1)
+ "?</br></br><select id='choice' name='attribute'><option selected='selected' value='makeSelection'>please choose</option>";
for (i = 0; i < vals.length; i++) {
html = html + "<option value='"+vals[i]+"'>"
+ vals[i] + "</option>";
}
html = html
+ "</select></br></br><input type='button' onclick='return sendChoice("
+ first + "," + last + "," + utt + ","
+ type + "," + pass
+ ")' value='Submit'></input>";
document.getElementById("utteranceDiv").innerHTML = html;
}
if (type === 'instance') {
html = "You have said the following to the virtual assistant: </br><i>'"
+ utt
+ "'</i></br></br>Given that you have said this and the choices you have made so far; </br> "
+ out
+ "</br><select id='choice' name='attribute'><option selected='selected' value='makeSelection'>please choose</option><option value='yes'>yes</option><option value='no'>no</option></select></br></br><input type='button' onclick='return sendChoice("
+ first
+ ","
+ last
+ ","
+ utt
+ ","
+ type
+ ","
+ pass
+ ")' value='Submit'></input>";
document.getElementById("utteranceDiv").innerHTML = html;
} else {
//done make final Page.
html = "Thank you this scenario is over.";
document.getElementById("utteranceDiv").innerHTML = html;
}
}
}
xmlhttp
.open(
"Post",
"http://"
+ server
+ "/DialogueRefinementWebExperiment/WebExperimentServlet",
true);
//xmlhttp.setRequestHeader("accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
console.log('before');
if (typ == "attribute") {
xmlhttp.send("first=" + first + "&last=" + last
+ "&mainType=" + type + "&att=" + attOrInstIndex
+ "&utt=" + utt + "&choice=" + choice + "&done=no");
} else if (typ == "instance") {
xmlhttp.send("first=" + first + "&last=" + last
+ "&mainType=" + type + "&indexResult="
+ attOrInstIndex + "&utt=" + utt + "&choice="
+ choice + "&done=" + choice);
}
}
}
The HTML is:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script>
window.onload = function init() {
server = window.location.host;
params = location.search.split("?")[1];
first = params.split("&")[0].split("=")[1];
last = params.split("&")[1].split("=")[1];
}
</script>
</head>
<body>
<div id="utteranceDiv">
When you are ready click Submit and the system will begin to ask you
questions in an attempt to find you a restaurant that you are happy
with.</br> <input type="button" onclick="return makeRequest()"
value="Select"></input>
</div>
<script type="text/javascript">
//see above for javascipt
</script>
</body>
</html>
the div gets updated after the first call:
<div id="utteranceDiv">
You have said the following to the virtual assistant: <br><i>'i want a
mexican restaurant at 7 pm in cupertino'
</i><br><br>Given that you have said this; <br> How about null. It is in
Mountain View; in Peninsula. There is a reservation at earlyNight.<br>
<select id="choice" name="attribute"><option selected="selected"
value="makeSelection">please choose</option>
<option value="yes">yes</option>
<option value="no">no</option></select><br><br><input type="button"
onclick="return sendChoice(eli,pincus,i want a mexican restaurant at 7 pm in
cupertino,instance,1)" value="Submit"></div>
I check your post, but i cant find any missing ")". The console doesnt tell you where to look?
I figured it out; it is because the arguments of the javascript function that get written on the updated page are strings and so need qoutes around them (one of them had spaces and thats why i didn't get a line number it messes up the parser)

Why can't I update this table with the same code used in another place using Javascript?

The table cell updates correctly to "" (empty) in the changeScore function, but that same cell does not change at all in the editUpdate function when I try to place the new score in there. It just stays empty. Any ideas?
function changeScore(playerKey)
{
var table = document.getElementById("scoreTable");
players[playerKey].score = players[playerKey].oldScore;
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
document.getElementById('inputArea').innerHTML = '<font size="6">Did <b>' + players[playerKey].name + '</b> take <b>' + players[playerKey].bid + '</b> trick(s)?</font><br /><button value="Yes" id="yesButton" onclick="editUpdate(' + playerKey + ', \'yes\')">Yes</button>&nbsp&nbsp&nbsp&nbsp<button value="No" id="noButton" onclick="editUpdate(' + playerKey + ', \'no\')">No</button>';
}
function editUpdate(thePlayerKey, answer)
{
var table = document.getElementById("scoreTable");
players[thePlayerKey].oldScore = players[thePlayerKey].score;
if (answer == "yes"){
**
}else{
**
}
table.rows[currentRound - 1].cells[thePlayerKey + 1].innerHTM = '<font color="' + players[thePlayerKey].font + '">' + players[thePlayerKey].score + '</font>';
document.getElementById('inputArea').innerHTML = '<button onclick="startRound()">Start Round</button>&nbsp&nbsp&nbsp&nbsp&nbsp<button onclick="edit()">Edit Scores</button>';
}
innerHTM should be innerHTML
This:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTM = '';
Should be:
table.rows[currentRound - 1].cells[playerKey + 1].innerHTML = '';
(Same for 2nd function)

CRM Javascript, multiple independent sets of script on the same OnLoad form

I am new to Javascript, I basically have a form to edit on CRM. I have two pieces of script, independent of each other, they both work fine on their own when I use the OnLoad feature, however when I put both sets of code into the same script developer (since its for the same form on CRM), one of them does not work.
Can anyone help and is there any special syntax to have multiple scripts on the same form?
Thanks
The Javascript is below:
var _roles = 'Compliance'; //array of security roles name
var _fields = 'new_pend'; // array of field schema names to enable
UpdateFields();
/* Functions */
function UpdateFields() {
var oXml = GetCurrentUserRoles();
if (oXml != null) {
var roles = oXml.selectNodes("//BusinessEntity/q1:name");
if (roles != null) {
for (i = 0; i < roles.length; i++) {
for (j = 0; j < _roles.length; j++) {
if (roles[i].text == _roles[j]) {
for (k = 0; k < _fields.length; k++) {
try {
document.getElementById(_fields[k]).Disabled = false;
} catch (e) {
}
}
return;
}
}
}
}
}
return;
}
function GetCurrentUserRoles() {
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>role</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>name</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>role</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkCriteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>systemuserid</q1:AttributeName>" +
" <q1:Operator>EqualUserId</q1:Operator>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:LinkCriteria>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", " http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
return (resultXml);
}
Hi everyone who has read this, I found a solution to the problem.
I used an If statement to define what the output should be based on an input into the function. This is shown in the code below, Use this code with the function GetCurrentUserRoles. Thanks for all the help.
if(UserHasRole("Collections") ==true)
{
crmForm.all.new_pend.Disabled = false;
return;
}
else if (UserHasRole("Collections") ==false)
{
crmForm.all.new_pend.Disabled = true;
return;
}
function UserHasRole(roleName)
{
//get Current User Roles, oXml is an object
var oXml = GetCurrentUserRoles();
if(oXml != null)
{
//select the node text
var roles = oXml.selectNodes("//BusinessEntity/q1:name");
if(roles != null)
{
for( i = 0; i < roles.length; i++)
{
if(roles[i].text == roleName)
{
//return true if user has this role
return true;
}
}
}
}
//otherwise return false
return false;
}

Storing data in JavaScript array

This is my jsp code where I am trying to push some data in javaScript array.
<%
int proListSize = proList.size();
ProfileDAO proDAO = null;
for(int i = 0, j=1; i < proListSize; i++){
proDAO = (ProfileDAO)proList.get(i);%>
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + <%= proDAO.getCode()%>);
<%} %>
And this is the function where I am trying to use it by using pop function.
function GenDemographicTag() {
var ptag = "<!-- Begin "+networkNameToUpperCase+" -->\n" ;
var t = "";
if (WhiteTagLabelDomain) {
ptag += "<iframe src=\"http://"+WhiteTagLabelDomainTrim+"/jsc/"+folderName+"/dm.html?";
} else {
ptag += "<iframe src=\"http://"+cdnName+"/jsc/"+folderName+"/dm.html?";
}
ptag += "n="+networkId+";";
for(var i = 0;i< entireArray.length;i++){
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString.split(':')[0];
var middle = combinedString.split(':')[1];
var leftSide = combinedString.split(':')[2];
t = "";
if ( $("proElementEnable_"+rightSide) && $("proElementEnable_"+leftSide).checked) {
if ( middle == "1") {
if ( $("zip").value.length <= 0) {
t = "0";
} else {
t = $("zip").value;
}
} else if ( $("targetList_"+rightSide) && $("targetList_"+rightSide).length > 0 && $("targetList_"+rightSide).options[0].value != "-1") {
t = makeProelementList($("targetList_"+rightSide));
}
ptag += leftSide+"=" + t+ ";";
}
proDAO = null;
}
ptag += "\" frameborder=0 marginheight=0 marginwidth=0 scrolling=\"no\" allowTransparency=\"true\" width=1 height=1>\n</iframe>\n<!-- end "+networkNameToUpperCase+" -->\n";
document.forms[0].tag.value = ptag;
}
Basically I am trying to get the data from proList and store it in javaScript array(entireArray)...so that I can use in the javascript function..but after doing the above I get a javaScript error as follow:
entireArray.push(3 + ":"+3 + ":" + d3);
entireArray.push(185 + ":"+5 + ":" + d4);
entireArray.push(2 + ":"+2 + ":" + d2);
entireArray.push(186 + ":"+5 + ":" + d9);
entireArray.push(183 + ":"+5 + ":" + d6);
entireArray.push(184 + ":"+5 + ":" + d7);
entireArray.push(187 + ":"+5 + ":" + da);
entireArray.push(445 + ":"+5 + ":" + db);
Reference Error:d3 is not defined.
what is the exact problem..?
The return type of splice is an ARRAY , so you can try following code
var combinedString = entireArray.splice(1,1);
var rightSide = combinedString[0].split(':')[0];
var middle = combinedString[0].split(':')[1];
var leftSide = combinedString[0].split(':')[2];
d3 should be in quotes. "d3"
You need to put the out of JSP in quotes.
entireArray.push(<%= proDAO.getNetworkmapId()%> + ":"+<%=proDAO.getAssetId()%> + ":" + '<%= proDAO.getCode()%>');

Converting firefox javascript to IE javascript

I've been trying to get some AJAX code that runs fine in FireFox to run in IE.
I'm running into some trouble with updating some tables in the script though. I've seen numerous other people have similar issues, but none of the solutions they've found have worked for me. The problem occurs first on the line
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
Where I'm getting the error "'null' is null or not an object"
I'm pretty sure that all of my other errors are of the same type as this one, my AJAX script and some accompanying javascript is below.
<script type="text/javascript">
<!--
//obtains the box address for a QE3 on the system for the given index
function getQE3BoxAddressHash(index)
{
var retVal = 0x00000100; //initial value for QE3 boxes
retVal |= (index & 0x000000FF);
return retVal;
}
//obtains the box address for a QED on the system for the given index
function getQEDBoxAddressHash(index)
{
var retVal = 0x00001300; //initial value for QED boxes
retVal |= ((index & 0x0000000F) << 4);
retVal |= ((index & 0x000000F0) >> 4);
return retVal;
}
-->
</script>
<script type="text/javascript">
<!--
var textSocket;
function fillTables()
{
if(textSocket.readyState != 4)
return;
var qe3Table = document.getElementById("QE3_TABLE");
var qedTable = document.getElementById("QED_TABLE");
var rawData = textSocket.responseText.split("::::");
var qe3Data = new Array();
var qedData = new Array();
var qe3Index = 0;
var qedIndex = 0;
for(var item in rawData)
{
if(rawData[item].indexOf("QA") != -1)
{
qe3Data[qe3Index++] = rawData[item];
}
else if(rawData[item].indexOf("QED") != -1)
{
qedData[qedIndex++] = rawData[item];
}
}
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
qedTable.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
for(var value in qe3Data)
{
var components = qe3Data[value].split("-");
if(components.length != 3)
continue;
qe3Table.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQE3BoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
for(var value in qedData)
{
var components = qedData[value].split("-");
if(components.length != 3)
continue;
qedTable.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQEDBoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
}
function initAjax()
{
try
{
// Opera 8.0+, Firefox, Safari
textSocket = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
textSocket = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
textSocket = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("A browser error occurred.");
return false;
}
}
}
textSocket.onreadystatechange=fillTables
}
function reloadTables()
{
textSocket.open("GET","ajax_scripts/get_connected_boxes.php",true);
textSocket.send(null);
}
function init()
{
initAjax();
reloadTables();
}
window.onload=init();
-->
</script>
The problem is probably with:
var qe3Table = document.getElementById("QE3_TABLE");
If you're running this script before the body is loaded, that won't exist. Check to see if that variable has anything in it.
I Tried both of your guys' fixes but they didn't seem to help. In the end, I converted all calls of the form:
qe3TableNew.innerHTML = ("<tr>\n" +" <th>Name</th>\n" +" <th>Status</th>\n" +" <th>View Status</th>\n" +"</tr>\n");
to
var row;
var cell;
var text;
var font;
row = document.createElement("tr");
qe3TableNew.appendChild(row);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Name");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Status");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("View Status");
cell.appendChild(text);
This seemed to solve it, so I believe it has to do with IE's inability to handle changes to innerHTML.
Thanks for the help guys.
At least one issue (which could produce the above symptoms) is the line:
window.onload=init();
Hint: the () operator executes the function immediately and evaluates to the return value. This in turn may allow the XHR handler (in certain situations) to fire at a time when the DOM may not be ready.
Happy coding.

Categories

Resources