Xml.TransformNode(xmldoc) is not supporting in Firefox,chrome,edge - javascript

This is the function iam calling to load the data in div
function createApproverList(div, locationId, value)
{
try
{
var url = "dbXML?conn=webddev&sql=Select logon_id, sec_last_name || ', ' || sec_first_name technician_name from w_security where rec_del_flg = 0 AND type_id = 3 order by sec_last_name";
var xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.load(url);
div.innerHTML = xml.transformNode(approverXSL.XSLDocument);
document.frmEntry.approverId.value = value;
}
catch (e) {
console.error(e.name + ': ' + e.message)
}
}
But it is working fine internet explorer and not in other browsers so, please help me by converting above one to support in firefox,chrome,edge browsers
Thanks in advance!...

Related

Store webkitSpeechRecognition in browser (indexeddb)

For a project I've implemented a web speech api in a website/Progressive Web App which translates spoken voice to text. This all works fine, however, I would also like to use this without access to internet.
My initial thought was that I could save my recognition object to a indexeddb and process it later. However, when I try to do this I get the following error:
DOMException: Failed to execute 'put' on 'IDBObjectStore': SpeechRecognitionEvent object could not be cloned.
While I do understand why I get this error, I have no clue on any alternative way of doing this or how I can solve this error.
My object looks as following:
When I try to serialize my object using JSON.stringify() I get the following:
I lose all of my information.
My code looks as follows:
function attachRecognition() {
recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.onstart = function(event) {
recognitionStarted = true;
};
recognition.onend = function(event) {
recognitionStarted = false;
};
recognition.onresult = function(event) {
var finalPhrase = '';
var interimPhrase = '';
var result;
for(var i=0; i<event.results.length; ++i) {
result = event.results[i];
if( result.isFinal ) {
finalPhrase = finalPhrase.trim() + ' ' + result[0].transcript;
}
else {
interimPhrase = interimPhrase.trim() + ' ' + result[0].transcript;
}
}
var input_field = $(related_input_field);
if (connected) {
input_field.val(input_field.val() + finalPhrase + ".");
}
// This is where I would store my event data in case there's no connection.
else {
set(related_input_field.attr("id"), event)
.then(() => {
console.log(related_input_field.attr("id") + ' data cached');
})
.catch(console.warn);
}
}
}
How can I solve this?

appendChild doesn't work in IE

The following snippet of code adds for javascript html to a page. It works in Chrome and Firefox, but in IE not.
xmlHttp.onload = function() {
if (xmlHttp.status === 200) {
var okToComeBack = true;
var responseJson = JSON.parse(xmlHttp.responseText);
var environmentDiv = document.createElement('div');
environmentDiv.setAttribute('class', 'container-environmentmarker');
environmentDiv.innerHTML = '<div class="container-environment"><div class="environment-marker"></div></div>';
document.body.appendChild(environmentDiv);
document.getElementsByClassName(that._config.environmentClass)[0].innerHTML = responseJson.nameOfEnvironment;
document.getElementsByClassName(that._config.environmentMarkerClass)[0].setAttribute('class', that._config.environmentMarkerClass + ' ' + that._config.environmentMarkerClassPrefix + responseJson.colourOfMarker);
if (responseJson.nameOfSite !== undefined) {
document.getElementsByClassName(that._config.siteNameClass)[0].innerHTML = responseJson.nameOfSite;
}
}
};
Do you have any idea why?

Call external Web Service using javascript CRM 2011 RU 12 (Rollup 12)

Until very recently we'd been using RU 11 within our Dynamics CRM 2011 application but have recently begun a project to eventually move to CRM 2015. We've upgraded to RU 12 and this is where things get fun!
I've managed to sort out a lot of the coding issues that were previously present but cannot for the life of me solve our issue of accessing an external web service, passing parameters along the way and retrieving data back.
At first I had trouble with the "CreateXmlHttp()" function but found a great answer online indicating that the following function would help:
function CreateXmlHttp()
{
var ref = null;
if (window.XMLHttpRequest) {
ref = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Older IE
ref = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
return ref;
}
This worked fine and as expected, it would have appeared that I could now connect to the service.
However, I am not retrieving any data and this is the issue that is tying me up in knots.
As background, the following is my code to declare a few integer variables before POSTING the xml through to the webservice.
parseInt(lngLicensNr);
parseInt(lngNrOfUsers);
parseInt(lngAnnualWorkingTime);
parseInt(lngIncludedHours);
parseInt(productType);
if (licenceType == 100000000) {
var licenseType = "ltUnlimitedMode";
lngIncludedHours = 1000000;
}
if (licenceType == 100000001) {
var licenseType = "ltHourlyMode";
}
if (lngLicensNr != null && lngNrOfUsers != null && lngAnnualWorkingTime != null && lngIncludedHours != null && productType != null && licenseType != null) {
var errMsg = "";
var errCount = 0;
var xml = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
xml += "<soap:Body>";
xml += "<GetBaseInstallationKey xmlns=\"http://www.keyservice.com/\">";
xml += "<licensNr>" + lngLicensNr + "</licensNr>";
xml += "<nrOfUsers>" + lngNrOfUsers + "</nrOfUsers>";
xml += "<annualWorkingTime>" + lngAnnualWorkingTime + "</annualWorkingTime>";
xml += "<includedHours>" + lngIncludedHours + "</includedHours>";
xml += "<productType>" + baseProduct + "</productType>";
xml += "<licenseType>" + licenseType + "</licenseType>";
xml += "</GetBaseInstallationKey>";
xml += "</soap:Body>";
xml += "</soap:Envelope>";
try {
Request = CreateXmlHttp();
} catch (ex) {
alert("An error occured while accessing the webservice.\n\n1. " + ex.name + " \n " + ex.message + "\n\n");
errCount = 1;
}
if (errCount == 0) {
try {
Request.open("POST", "http://web01:8080/KeyWebService/KeyWebService.asmx", false);
} catch (ex) {
alert("An error occured while accessing the webservice.\n\n2. " + ex.name + " \n " + ex.message + "\n\n");
errCount = 1;
}
}
if (errCount == 0) {
try {
Request.setRequestHeader("SOAPAction", "http://www.keyservice.com/GetKey");
Request.setRequestHeader("Host", "web01:8080");
Request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
Request.setRequestHeader("Content-Length", xml.length);
Request.send(xml);
var xmlDoc = Request.responseXML;
} catch (ex) {
alert("An error occured while accessing the webservice.\n\n3. " + ex.name + " \n " + ex.message + "\n\n");
errCount = 1;
}
}
if (errCount == 0 || Request.responseXML != null) {
baseKey = Request.responseXML.text;
} else {
baseKey = "No key generated";
}
}
if (lngLicensNr == null || lngNrOfUsers == null || lngAnnualWorkingTime == null || lngIncludedHours == null || productType == null || licenseType == null) {
alert('Not all parameters have been entered - it is not possible to generate a key without all parameters');
}
Prior to RU 12, the code worked absolutely fine and the last variable "baseKey" was retrieved from the web service.
However, the whole process works perfectly fine now in that it seems to connect ok but just does not retrieve a "baseKey" from the service.
I believe that the issue may be related to deprecated end points or schemas or even just deprecated code that returns and displays the value (i.e. var xmlDoc = Request.responseXML;) but I'm not sure where to resolve.
If anyone has any ideas or can point me in the right direction it would be a big help.
we had similar requirement to call an external Web-service to retrieve the latest contract of a contact and show it on Contact Form.
We had our own definition of latest contract that was implement in a webserivce. So i have to call that webservice on Contact Form Load and pull the data. I could not find an answer. So i am posting my workaround for this.
I had written a plugin that executes on the retrieve of Contact. From the plugin i had call the Webservice and updates the contact fields.
var javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = 104857600; //200 MB unicode
StringBuilder URI = new StringBuilder();
URI.Append(crmRestWebServiceUrl).Append(webServiceMethod);
var request = (HttpWebRequest)WebRequest.Create(URI.ToString());
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
//Serialize request object as JSON and write to request body
if (latestMembershipRequest != null)
{
var stringBuilder = new StringBuilder();
javaScriptSerializer.Serialize(latestMembershipRequest, stringBuilder);
var requestBody = stringBuilder.ToString();
request.ContentLength = requestBody.Length;
var streamWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
streamWriter.Write(requestBody);
streamWriter.Close();
}
var response = request.GetResponse();
//Read JSON response stream and deserialize
var streamReader = new System.IO.StreamReader(response.GetResponseStream());
var responseContent = streamReader.ReadToEnd().Trim();
LatestMembershipResponse latestMembershipResponse = javaScriptSerializer.Deserialize<LatestMembershipResponse>(responseContent);
ContactToUpdate["gr_membershiptitle"] = latestMembership.MembershipTitle;
ContactToUpdate["gr_membershipstartdate"] = Convert.ToDateTime(latestMembership.MembershipStartDate);
ContactToUpdate["gr_membershipenddate"] = Convert.ToDateTime(latestMembership.MembershipEndDate);
ContactToUpdate["gr_membershipstatus"] = latestMembership.MembershipStatus;
service.Update(ContactToUpdate);

Firefox plugin for SSL

I am trying to make a plugin for Mozilla which prints simple SSL details like Name and certificate is valid till what date.
Here is my CODE :
var data = require("sdk/self").data;
var text_entry = require("sdk/panel").Panel({
width: 412,
height: 400,
contentURL: data.url("text-entry.html"),
contentScriptFile: data.url("get-text.js")
});
require("sdk/widget").Widget({
label: "Text entry",
id: "text-entry",
contentURL: "http://www.mozilla.org/favicon.ico",
panel: text_entry,
});
text_entry.on("show", function() {
text_entry.port.emit("show");
});
text_entry.port.on("text-entered", function (text) {
console.log(text);
var requrl = require("sdk/tabs").activeTab.url;
console.log(requrl);
const {Ci,Cc} = require("chrome");
//var req = new XMLHttpRequest();
var req = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
req.open('GET', requrl, false);
req.onload = function(e) {
console.log(req);
let channel = req.channel;
console.log(requrl);
if (! channel instanceof Ci.nsIChannel) {
console.log("No channel available\n");
return;
}
console.log(requrl);
var secInfo = req.securityInfo;
var cert = secInfo.QueryInterface(Ci.nsISSLStatusProvider).SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert ;
var validity = cert.validity.QueryInterface(Ci.nsIX509CertValidity);
console.log(requrl);
console.log("\tCommon name (CN) = " + cert.commonName + "\n");
console.log("\tOrganisation = " + cert.organization + "\n");
console.log("\tIssuer = " + cert.issuerOrganization + "\n");
console.log("\tSHA1 fingerprint = " + cert.sha1Fingerprint + "\n");
console.log("\tValid from " + validity.notBeforeGMT + "\n");
console.log("\tValid until " + validity.notAfterGMT + "\n");
};
});
It says, XMLHttpRequest is not defined. Also the channel structure is empty when printed to console.
Not exactly sure where your code is broken or why (as I'm to lazy to replicate the missing pieces like the text-entry.html).
Anyway, here is a fast test that works for me in both, and SDK add-on and Scratchpad:
// Save as your main.js.
// Alternatively execute in a Scratchpad in about:newTab.
var sdk = false;
if (!("Cc" in this)) {
try {
// add-on SDK version
this.Cc = require("chrome").Cc;
this.Ci = require("chrome").Ci;
this.log = console.error.bind(console);
this.sdk = true;
log("using SDK");
}
catch (ex) {
// Scratchpad on about:newtab version
this.Cc = Components["classes"];
this.log = console.log.bind(console);
log("using scratchpad");
}
}
let r = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
r.open("GET", "https://tn123.org/");
r.onloadend = function(e) {
let ok = "OK";
try {
log(e);
// Note: instanceof is an implicit QueryInterface!
log(this.channel instanceof Ci.nsIChannel);
log(this.channel.securityInfo instanceof Ci.nsISSLStatusProvider);
let status, cert;
log(status = this.channel.securityInfo.SSLStatus);
log(status.cipherName);
log(cert = status.serverCert);
log("Common name (CN) = " + cert.commonName);
log("Organisation = " + cert.organization);
log("Issuer = " + cert.issuerOrganization);
log("SHA1 fingerprint = " + cert.sha1Fingerprint);
log("Valid from " + cert.validity.notBeforeGMT);
log("Valid until " + cert.validity.notAfterGMT);
for (let k of Object.keys(cert)) {
if (k[0].toUpperCase() === k[0]) {
// skip constants
continue;
}
let v = cert[k];
if (typeof v === "function") {
continue;
}
log(k + ": " + v);
}
}
catch (ex) {
log("Caught exception", ex);
ok = ex;
}
if (sdk) {
require("notifications").notify({
title: "Test done",
text: "HTTPS test done; result=" + ok
});
}
log("HTTPS test done; result=" + ok);
};
r.send();
PS: I'm using console.error in the SDK, because:
If you're developing your add-on using the Extension Auto-installer,
then the add-on is installed in Firefox, meaning that messages will
appear in the Browser Console. But see the discussion of logging
levels: by default, messages logged using log(), info(), trace(), or
warn() won't be logged in these situations.
Have you written this in the content script? If so, you can't make requests from the content script (which is why it says it does not exist). You need to write this in main.js. If you want to communicate with your content script (html, window, etc) you'll have to use message passing: port.emit and addon.emit to send messages and port.on and addon.on to listen for messages.

Javascript does not recognise dynamic div content

I have a script i have been battling with now for like a week.
I have a page which has a div with id ("content"). Now I loaded some content, a form contained in a div tag to be specific, into this div VIA Ajax, and it is displaying fine
Now, the challenge is - When the form is submitted, Im am calling a function that will disable all the field on the element in that div tag. I always get the error "undefined".
It seems that the div, that i brought in to the page isn't recognized by javascript..
I have searched google, bing, yahoo..i just havent found the solution yet...
Please, what do I do??
I have included the code below --
+++++++++
The code below for my external javascript file
++++++++++++++++++++
// JavaScript Document
var doc = document;
var tDiv;
var xmlHttp;
var pgTitle;
function getXMLObj(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
Obj = new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
Obj = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support Ajax!");
}
return Obj;
}
function loadCont(toLoad, view){
doc.getElementById('loadBlank').innerHTML = '<div id="loading">Processing Request...</div>';
var url;
switch(toLoad){
case 'CI':
pgTitle = "Administration - Company Information";
url = "comp_info.php?v=" + view + "&sid=" + Math.random();
break;
case 'JB':
pgTitle = "Administration - Jobs";
url = "jobs.php?v=" + view + "&sid=" + Math.random();
break;
case 'US':
pgTitle = "Administration - Users";
url = "users.php?v=" + view + "&sid=" + Math.random();
break;
case 'EP':
pgTitle = "Administration - Employees";
url = "emp.php?v=" + view + "&sid=" + Math.random();
break;
case 'AP':
pgTitle = "Administration - Recruitments";
url = "applicants.php?v=" + view + "&sid=" + Math.random();
break;
case 'JV':
pgTitle = "Administration - Recruitments";
url = "jobvacancy.php?v=" + view + "&sid=" + Math.random();
break;
}
xmlHttp = getXMLObj();
if (xmlHttp !== null && xmlHttp !== undefined){
xmlHttp.onreadystatechange = loadingContent;
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}
}
function loadingContent(){
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
//Show the loading and the title, but hide the content...
if (xmlHttp.status == 200){
doc.getElementById('dMainContent').innerHTML = parseScript(xmlHttp.responseText);
doc.getElementById('loadBlank').innerHTML = '';
}
else{
doc.getElementById('dMainContent').innerHTML = 'Sorry..Page not available at this time. <br />Please try again later';
doc.getElementById('loadBlank').innerHTML = '';
}
}
if (xmlHttp.readyState < 4){
//Show the loading and the title, but hide the content...
doc.getElementById('ActTitle').innerHTML = pgTitle;
doc.getElementById('dMainContent').innerHTML = '';
}
}
function valCompInfo(){
//First Disable All the elements..
alert('I was hree');
DisEnaAll('CompForm');
//Now..lets validate the entries..
}
function DisEnaAll(contId){
//alert(doc.getElementById(contId).elements);
var theId = doc.getElementById(contId).elements;
try{
var numElems = theId.length;
for (var i=0; i < (numElems - 1); i++){
(theId[i].disabled == false) ? (theId[i].disabled = true) : (theId[i].disabled = false);
}
}
catch(e){
var msg = "The following error occurred: \n\n";
msg += e.description
alert(msg);
}
}
// http://www.webdeveloper.com/forum/showthread.php?t=138830
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}
This code is on the main page where the javascript is
<div id="dMainContent">
</div>
</body>
</html>
And finally, the content of the page i am loading via ajax..
<div style="width:738px" id="CompForm">
<div class="tdright">
<?php echo $btnNm; ?>
</div>
</div>
That's the code..
Thanks
The issue is with div tag (id "CompForm") which is not a HTML form.
"elements" is a collection of the form element not div element. So when trying to access div.elements the property is undefined.
See MSDN, form.elements is part of DOM level 1 (according to MSDN)
http://msdn.microsoft.com/en-us/library/ms537449%28v=VS.85%29.aspx
Add your Javascript functions or external JS file to the original page.
this is not JavaScript....
doc.getElementById(contId).elements
but is used in your JavaScript... you will definitely not get anything. (null)
I don't think this is valid either:
theId[i].disabled == false
EDIT: Note per comments: this is NOT the answer :) See comments for details of why.
Left as an answer simply as a learning aid aid as suggested.
Shouldn't
xmlHttp.onreadystatechange = loadingContent;
be
xmlHttp.onreadystatechange = loadingContent();
or
loadingContent();
and that function should return a value if you want to assign it like that...

Categories