Can this function return DOM elements? - javascript

For some reason parsing this XML string...I'm getting this error at dom.async = false;
...in theory this should be possible?
$(document).ready( function(){
function parseXml(xml) {
var dom = null;
if (window.DOMParser) {
try {
dom = (new DOMParser()).parseFromString(xml, "text/xml");
}
catch (e) { dom = null; }
}
else if (window.ActiveXObject) {
try {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;
if (!dom.loadXML(xml)) // parse error ..
window.alert(dom.parseError.reason + dom.parseError.srcText);
}
catch (e) { dom = null; }
}
else
alert("oops");
return dom;
}
});

According to Here IE11 Cannot be detected by window.ActiveXObject.

Related

Can I open the URL automaticly when I scan with WebQR

I am a programmer and I just made a simple webapp, with webview in Android studio. I have everything working except one thing. I used the WebQR set from LazarSoft. In my webapp part I have a file called webqr.js (found beneath) with the following content.
What I am trying to do is when a QR-code is scanned I want to open the result (if it is an URL) automatic in the same browser window. Now it just shows only the result.
Any help would be much appreciated.
var gCtx = null;
var gCanvas = null;
var c=0;
var stype=0;
var gUM=false;
var webkit=false;
var moz=false;
var v=null;
var imghtml='<div id="qrfile"><canvas id="out-canvas" width="320" height="240"></canvas>'+
'<div id="imghelp">drag and drop a QRCode here'+
'<br>or select a file'+
'<input type="file" onchange="handleFiles(this.files)"/>'+
'</div>'+
'</div>';
var vidhtml = '<video id="v" autoplay></video>';
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
if(files.length>0)
{
handleFiles(files);
}
else
if(dt.getData('URL'))
{
qrcode.decode(dt.getData('URL'));
}
}
function handleFiles(f)
{
var o=[];
for(var i =0;i<f.length;i++)
{
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
gCtx.clearRect(0, 0, gCanvas.width, gCanvas.height);
qrcode.decode(e.target.result);
};
})(f[i]);
reader.readAsDataURL(f[i]);
}
}
function initCanvas(w,h)
{
gCanvas = document.getElementById("qr-canvas");
gCanvas.style.width = w + "px";
gCanvas.style.height = h + "px";
gCanvas.width = w;
gCanvas.height = h;
gCtx = gCanvas.getContext("2d");
gCtx.clearRect(0, 0, w, h);
}
function captureToCanvas() {
if(stype!=1)
return;
if(gUM)
{
try{
gCtx.drawImage(v,0,0);
try{
qrcode.decode();
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
}
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function read(a)
{
var html="<br>";
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
html+="<a target='_blank' href='"+a+"'>"+a+"</a><br>";
html+="<b>"+htmlEntities(a)+"</b><br><br>";
document.getElementById("result").innerHTML=html;
}
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
function success(stream) {
if(webkit)
v.src = window.webkitURL.createObjectURL(stream);
else
if(moz)
{
v.mozSrcObject = stream;
v.play();
}
else
v.src = stream;
gUM=true;
setTimeout(captureToCanvas, 500);
}
function error(error) {
gUM=false;
return;
}
function load()
{
if(isCanvasSupported() && window.File && window.FileReader)
{
initCanvas(800, 600);
qrcode.callback = read;
document.getElementById("mainbody").style.display="inline";
setwebcam();
}
else
{
document.getElementById("mainbody").style.display="inline";
document.getElementById("mainbody").innerHTML='<p id="mp1">QR code scanner for HTML5 capable browsers</p><br>'+
'<br><p id="mp2">sorry your browser is not supported</p><br><br>'+
'<p id="mp1">try <img src="firefox.png"/> or <img src="chrome_logo.gif"/> or <img src="Opera-logo.png"/></p>';
}
}
function setwebcam()
{
document.getElementById("result").innerHTML="- scanning -";
if(stype==1)
{
setTimeout(captureToCanvas, 500);
return;
}
var n=navigator;
document.getElementById("outdiv").innerHTML = vidhtml;
v=document.getElementById("v");
if(n.getUserMedia)
n.getUserMedia({video: true, audio: false}, success, error);
else
if(n.webkitGetUserMedia)
{
webkit=true;
n.webkitGetUserMedia({video:true, audio: false}, success, error);
}
else
if(n.mozGetUserMedia)
{
moz=true;
n.mozGetUserMedia({video: true, audio: false}, success, error);
}
//document.getElementById("qrimg").src="qrimg2.png";
//document.getElementById("webcamimg").src="webcam.png";
document.getElementById("qrimg").style.opacity=0.2;
document.getElementById("webcamimg").style.opacity=1.0;
stype=1;
setTimeout(captureToCanvas, 500);
}
function setimg()
{
document.getElementById("result").innerHTML="";
if(stype==2)
return;
document.getElementById("outdiv").innerHTML = imghtml;
//document.getElementById("qrimg").src="qrimg.png";
//document.getElementById("webcamimg").src="webcam2.png";
document.getElementById("qrimg").style.opacity=1.0;
document.getElementById("webcamimg").style.opacity=0.2;
var qrfile = document.getElementById("qrfile");
qrfile.addEventListener("dragenter", dragenter, false);
qrfile.addEventListener("dragover", dragover, false);
qrfile.addEventListener("drop", drop, false);
stype=2;
}
Welcome to JavaScript, may you long prosper with its many uses!
As you are new to JavaScript, you may not know its Browser API, but fear not!
What you are looking for is window.open
Its syntax is simple:
window.open("http://example.com")
So, when you get the url from you qr decoder, all you have to do is window.open the URL, and viola, the window will appear in a new tab!
Now if you want to open in the same browser window, then you want to use
window.location.replace("http://example.com")
This will redirect the same tab, instead of a new one!
To implement this in your program, take a look at this read function:
function read(a) {
// If it's a URL, open in here
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
window.location.replace(a)
}
Hope I could help!

Using same Ajax function to return content into multiple divs

We have a js ajax call we are using to pull content and placing them in different divs on our page.
We have been creating a new function for each call, but would like to just use one function for them all. In attempting this - it only updates the last div position requested.
Here are the requests:
<script type="text/javascript">
sendRequestFS('http://ourdomain.com/somepage.html', 'csad');
sendRequestFS('http://ourdomain.com/somepage1.html', 'fsad');
sendRequestFS('http://ourdomain.com/somepage2.html', 'tilead');
</script>
The divs on the page:
<div id = 'csad'>CS Here</div>
<div id = 'fsad'>FS Here</div>
<div id = 'tilead'>Tiles Here</div>
And the function that we are using ... is there some way to use this same function each time?
function createRequestObjectFS()
{
var returnObj = false;
if(window.XMLHttpRequest) {
returnObj = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
returnObj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
returnObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return returnObj;
}
var httpFS = createRequestObjectFS();
var targetFS;
// This is the function to call, give it the script file you want to run and
// the div you want it to output to.
function sendRequestFS(scriptFileFS, targetElementFS)
{
targetFS = targetElementFS;
try{
// alert ("RQFS File: " + scriptFileFS + " Target : " + targetElementFS);
httpFS.open('get', scriptFileFS, true);
}
catch (e){
document.getElementById(targetFS).innerHTML = e;
return;
}
httpFS.onreadystatechange = handleResponseFS;
httpFS.send();
}
function handleResponseFS()
{
if(httpFS.readyState == 4) {
try{
// alert ("HRQFS");
var strResponseFS = httpFS.responseText;
document.getElementById(targetFS).innerHTML = strResponseFS;
} catch (e){
document.getElementById(targetFS).innerHTML = e;
}
}
}
I rearranged your functions to make it work: http://jsfiddle.net/q2Za2/1/
function createRequestObjectFS()
{
var returnObj = false;
if(window.XMLHttpRequest) {
returnObj = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
returnObj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
returnObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return returnObj;
}
// This is the function to call, give it the script file you want to run and
// the div you want it to output to.
function sendRequestFS(scriptFileFS, targetElementFS)
{
var httpFS = createRequestObjectFS();
var targetFS;
function handleResponseFS()
{
if(httpFS.readyState == 4) {
try {
//alert ("HRQFS");
var strResponseFS = httpFS.responseText;
document.getElementById(targetFS).innerHTML = strResponseFS;
} catch (e){
document.getElementById(targetFS).innerHTML = e;
}
}
}
targetFS = targetElementFS;
try{
// alert ("RQFS File: " + scriptFileFS + " Target : " + targetElementFS);
httpFS.open('get', scriptFileFS, true);
}
catch (e){
document.getElementById(targetFS).innerHTML = e;
return;
}
httpFS.onreadystatechange = handleResponseFS;
httpFS.send();
}
sendRequestFS('https://r3dux.com/test_files/1.php', 'csad');
sendRequestFS('https://r3dux.com/test_files/2.php', 'fsad');
sendRequestFS('https://r3dux.com/test_files/3.php', 'tilead');

Adding XML element using Jquery

I have been working on adding XML element to XML structure without success, here is my code.
var parseXml;
if (window.DOMParser) {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
}
else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
}
else {
parseXml = function() { return null; }
}
var xmlTree = parseXml("<root></root>");
function add_children(child_name,parent_name)
{
str = '<'+child_name+'></'+child_name+'>';
//strXML = parseXml(str);
$(xmlTree).find(parent_name).append(str);
var xmlString = (new XMLSerializer()).serializeToString(xmlTree);
console.log(xmlString);
}
add_children("apple","root");
add_children("orange","root");
add_children("lychee","root");
but console is showing <root/> all three times
The problem is that you are creating the node in the Html document, not in the XML one, so you can't append it. Change this line:
str = '<'+child_name+'></'+child_name+'>';
For this one:
str = xmlTree.createElement(child_name);
See the working code in http://jsfiddle.net/W9Wpb/

construct xml string from parsed xml

My code for parsexml:
var parseXml = function (xml) {
var dom = null;
if (window.DOMParser) {
try {
dom = (new DOMParser()).parseFromString(xml, "text/xml");
}
catch (e) { dom = null; }
}
else if (window.ActiveXObject) {
try {
dom = new ActiveXObject('Microsoft.XMLDOM');
dom.async = false;
if (!dom.loadXML(xml)) // parse error ..
window.alert(dom.parseError.reason + dom.parseError.srcText);
}
catch (e) { dom = null; }
}
else
alert("cannot parse xml string!");
return dom;
}
now suppose
s="<a>random</a>";
b=parseXml(s);
now I want to get s back from b. How do I do that?
You need an XMLSerializer in most browsers and the xml property of XML nodes in older version of IE:
function serializeXmlNode(xmlNode) {
if (typeof window.XMLSerializer != "undefined") {
return new window.XMLSerializer().serializeToString(xmlNode);
} else if (typeof xmlNode.xml != "undefined") {
return xmlNode.xml;
}
return "";
}
var xmlStr = serializeXmlNode(b);
You need a XMLSerializer (MDN docu) object for converting your XML tree back to a string:
var ser = new XMLSerializer();
s = ser.serializeToString( b );

ajax form issue IE

I have the following code that works in every browser but IE. When click on the submit button of the form I get no response at all from IE.
form has this value: onsubmit="sendform(this);return false;"
<script type="text/javascript">
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.status);
//alert(http_request.responseText);
toggleDiv('stylized');
showtoggleDiv('success');
} else {
alert('There was a problem with the request.');
}
}
};
http_request.open('GET', url, true);
http_request.send(null);
}
function sendform(el) {
var sub = el.getElementsByTagName('input');
query = new Array();
for (i in sub) {
if (sub[i].name) {
query.push(sub[i].name + '=' + sub[i].value);
}
}
query = '?' + query.join('&');
makeRequest("http://markburnettinternational.com/sitelokpw/members/test.php" + query);
}
</script>
<script language="javascript">
function toggleDiv(divid) {
if (document.getElementById(divid).style.display == 'none') {
document.getElementById(divid).style.display = 'block';
} else {
document.getElementById(divid).style.display = 'none';
}
}
</script>
<script>
function showtoggleDiv(divid) {
document.getElementById(divid).style.display = 'block';
}
</script>
Turn on the browser's debugger and put a breakpoint in sendform() and walk through it and see what happens. Alternately turning on the javascript console can give you vital feedback about what's going on.
There are at least three problems with this piece of code:
var sub = el.getElementsByTagName('input');
query = new Array();
for (i in sub) {
if (sub[i].name) {
query.push(sub[i].name + '=' + sub[i].value);
}
}
First, always declare your variables within the local scope using var, so use
var query = new Array();
for (var i in sub) {
Second, getElementsByTagName returns a NodeList, which is an array-like object. Never iterate over array(-like object)s using a for … in loop, always use an ordinary for loop.
Third, always use encodeURIComponent to properly encode query parameters:
for (var i = 0, len = sub.length; i < len; i++) {
if (sub[i].name) {
query.push(sub[i].name + '=' + encodeURIComponent(sub[i].value));
}
}
This might solve your IE issue.

Categories

Resources