How to serialize HTML DOM to XML in IE 8? - html

Is there a way to do it(serialization of HTML DOM into XML) in IE 8 or any other older version of IE.
In firefox :
var xmlString = new XMLSerializer().serializeToString( doc );
does it.I haven't tried it, though.
XMLSerializer causes error in IE 8, that it is not defined.

var objSerializeDOM = {
//Variable to hold generated XML.
msg : "",
serializeDOM : function() {
dv = document.createElement('div'); // create dynamically div tag
dv.setAttribute('id', "lyr1"); // give id to it
dv.className = "top"; // set the style classname
// set the inner styling of the div tag
dv.style.position = "absolute";
// set the html content inside the div tag
dv.innerHTML = "<input type='button' value='Serialize' onClick='objSerializeDOM.createXML()'/>"
"<br>";
// finally add the div id to ur form
document.body.insertBefore(dv, document.body.firstChild);
},
/**
* XML creation takes place here.
*/
createXML : function() {
objSerializeDOM.msg += "";
objSerializeDOM.msg += "<?xml version='1.0' encoding='UTF-8'?>\n\n";
// Get all the forms in a document.
var forms = document.forms;
for ( var i = 0; i < forms.length; i++) {
// Get all the elements on per form basis.
elements = document.forms[i].elements;
objSerializeDOM.msg += "<FORM name=\"" + forms[i].name + "\" method=\""
+ forms[i].method + "\" action=\"" + forms[i].action + "\">\n\n";
for ( var j = 0; j < elements.length; j++) {
objSerializeDOM.msg += " <" + elements[j].tagName + " type=\""
+ elements[j].type + "\"" + " name=\""
+ elements[j].name + "\"" + " Value =\""
+ elements[j].value + "\" />\n";
}
alert(document.forms[i].elements[1].event);
}
objSerializeDOM.msg += "\n\n</FORM>\n\n";
alert(objSerializeDOM.msg);
objSerializeDOM.writeToFile(objSerializeDOM.msg);
},
/**
* Writes the msg to file at pre-specified location.
* #param msg
* the XML file created.
*/
writeToFile : function(msg) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.CreateTextFile("c:\\myXML.xml", true);
fh.WriteLine(msg);
fh.Close();
}
};
objSerializeDOM.serializeDOM();
I wrote this JS, I run this javascript using GreaseMonkey4IE. This simply puts a button on every page of the domain you specify in GM4IE. On click of that button it will parse the HTML document and create an XML file. It will also display the same as an alert first and will save the XML in your local drive on path specified.
There a still many improvements I am planning to do, but yes it works and may be give you guys an idea.The program is self-explanatory, I hope.
please have a look here How to get Events associated with DOM elements?Thanks

Related

Exception: Conversion from text/html to application/pdf failed - from yesterday

I was saving my emails as PDF. It was working well. It stopped working for the last few days with the error
Exception: Conversion from text/html to application/pdf failed
It is also reported by someone here :
It just stopped working - google-app-script google-drive-api createFile
function saveGmailAsPDF() {
var gmailLabels = "TESTING";
var driveFolder = "TEST2";
var threads = GmailApp.search("in:" + gmailLabels, 0, 5);
if (threads.length > 0) {
/* Google Drive folder where the Files would be saved */
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
/* Gmail Label that contains the queue */
var label = GmailApp.getUserLabelByName(gmailLabels) ?
GmailApp.getUserLabelByName(gmailLabels) : GmailApp.createLabel(driveFolder);
for (var t=0; t<threads.length; t++) {
//threads[t].removeLabel(label);
var msgs = threads[t].getMessages();
var html = "";
var attachments = [];
var subject = threads[t].getFirstMessageSubject();
/* Append all the threads in a message in an HTML document */
for (var m=0; m<msgs.length; m++) {
var msg = msgs[m];
html += "From: " + msg.getFrom() + "<br />";
html += "To: " + msg.getTo() + "<br />";
html += "Date: " + msg.getDate() + "<br />";
html += "Subject: " + msg.getSubject() + "<br />";
html += "<hr />";
html += msg.getBody().replace(/<img[^>]*>/g,"");
html += "<hr />";
var atts = msg.getAttachments();
for (var a=0; a<atts.length; a++) {
attachments.push(atts[a]);
}
}
/* Save the attachment files and create links in the document's footer */
if (attachments.length > 0) {
var footer = "<strong>Attachments:</strong><ul>";
for (var z=0; z<attachments.length; z++) {
var file = folder.createFile(attachments[z]);
footer += "<li><a href='" + file.getUrl() + "'>" + file.getName() + "</a></li>";
}
html += footer + "</ul>";
}
/* Convert the Email Thread into a PDF File */
//The PDF craeted is damaged by the below code
//var blob = Utilities.newBlob(html, "application/pdf").setName("mail" + ".pdf");
//var theFolderId = '{FOLDER ID}';
//var parentFolder = DriveApp.getFolderById(theFolderId);
//folder.createFile(blob);
// PDF is damaged by the below code
//var html = "<h1>Hello world</h1>";
//var blob = Utilities.newBlob(html, "application/pdf", "text.pdf");
//DriveApp.createFile(blob);
//the below code was working well.
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
//the bellow line is giving the error for the last few days
//Error : Exception: Conversion from text/html to application/pdf failed
folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf");
tempFile.setTrashed(true);
}
}
}
This seems to be an ongoing bug. It seems that it has already been reported to Google Issue Tracker. Go to the issue and click the white star (☆) at the top-left (just left of the issue ID) to increase its priority.

How do I make a JSON object produce HTML on the page

Here is my JSON
var gal = [
{
"folder":"nu_images",
"pic":"gd_42.jpg",
"boxclass":"pirobox_gall",
"alt":"Rand Poster 1",
"title":"Rand Poster 1",
"thfolder":"th",
"thumbpic":"th_gd_42.jpg"
},
{
"folder":"nu_images",
"pic":"gd_13.jpg",
"boxclass":"pirobox_gall",
"alt":"Explosive Pixel Design",
"title":"Explosive Pixel Design",
"thfolder":"th",
"thumbpic":"th_gd_13.jpg"
}
];
and here is my for loop
for (i = 0; i < gal.length; i++) {
document.getElementById("gallery").innerHTML = "" + "<img src=\"" + "http:\/\/galnova.com\/" + gal[i].folder + "\/" + "th\/" + gal[i].thumbpic + "\"" + "border=\"0\"" + "alt=\"" + gal[i].alt + "\"" + "title=\"" + gal[i].title + "\"\/>" + ""
};
I am trying to make my JSON show all of the objects in HTML one after the other. I can get it to show the first one or whatever number I put into the array but I don't know how to make it generate a list of them.
Here is a link to my jsfiddle. Any help you can offer would be greatly appreciated.
http://jsfiddle.net/o7cuxyhb/10/
It's being generated here <p id="gallery"></p> just not correctly.
You're overwriting your html with every loop iteration:
document.getElementById("gallery").innerHTML = ...
^---
Perhaps you want something more like
document.getElementById("gallery").innerHTML += ...
^---
which will concatenation the original html contents with your new stuff.
And technically, you shouldn't be doing this in a loop. Changing .innerHTML like that causes the document to be reflowed/re-rendered each time you change .innerHTML, which gets very expensive when you do it in a loop. You should be building your html as a plain string, THEN adding it to the dom.
e.g.
var str = '';
foreach(...) {
str += 'new html here';
}
document.getElementById("gallery").innerHTML += str;
for (i = 0; i < gal.length; i++) {
document.getElementById("gallery").innerHTML += "" + "<img src=\"" + "http:\/\/galnova.com\/" + gal[i].folder + "\/" + "th\/" + gal[i].thumbpic + "\"" + "border=\"0\"" + "alt=\"" + gal[i].alt + "\"" + "title=\"" + gal[i].title + "\"\/>" + "" };
Add a += instead of an = after innerHTML
Try this:
function displayJson(jsonArray){
var container = document.getElementById("gallery");
for (var i=0; i<jsonArray.length; i++){
var newElement = document.createElement("a").innerHTML = jsonToHtml(jsonArray[i])
container.appendChild(newElement);
}
}
function jsonToHtml(jsonObj){
//Define your dom object here
var el = document.createElement("a").innerHTML = '' // you code here
...
return el;
}
displayJson(gal);

Javascript ReGEX for JSON

This is all so confusing, I've seen so many examples of how to do different things and cannot seem to find a valid example for what I am trying to do.
I'm using the YQL for the stock quotes only to get just the major indexes, DOW S&P 500 and NASDAQ.
The project is getting the data and working, but I need to determine if the stock value is returning + or - (up or down).
if the market is up or flat, I want to add a CSS class to set it to green, if it is down, I want to set a CSS to red.
One other issue, this only seems to work when I place the function between the head and body, not in the head, not in the body.
<script type="text/javascript">
function stock_quotes(obj)
{
var items = obj.query.results.quote;
var output = '';
var num_quotes = items.length;
items[0].symbol = "DOW ";
items[1].symbol = "NASDAQ ";
items[2].symbol = "S&P 500 ";
//var posquote = {"\d\.?\d{0,9}\.\d{0,9}\s\+"};
//var negquote = {"\d\.?\d{0,9}\.\d{0,9}\s\-"};
for (var i = 0; i < num_quotes; i++) {
var link = items[i].url;
var symbl = items[i].symbol;
var Change_PercentChange = items[i].Change_PercentChange;
var LastTradePriceOnly = items[i].LastTradePriceOnly;
output += "<table><tr><td>" + "<a href='" + link + "'>" + symbl + "</a>" + LastTradePriceOnly + " " + Change_PercentChange + "</td></tr></table>";
}
// Place news stories in div tag
document.getElementById('results').innerHTML = output;
}
This is the HTML with the query
<div id='results'></div>
<script type="text/javascript" src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22DOW%22%2C%22%5EIXIC%22%2C%22%5EGSPC%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=stock_quotes'></script>
Ideally I'd like to predefine the html elements which would make it easier to set the css class but one headache at a time.
In the end, this seemed to work just fine
var match_nas_neg = nas_result.match(/\-/);

Pass parameter to another page to generate listview from Json

Hello I'm using this js to pass the url parameter and it's working just fine, but my problem is that when I define the path to the JSON file I don't want to use the id of the item...I want to use another Id. For example: I have the following item:
{"id":"1",
"name":"Winery",
"street":"Chile",
"number":"898",
"phone":"4204040",
"mail":"winery#hotmail.com",
"web":"www.winery.com",
"lat":"-32.891638",
"long":"-68.846522",
"id_localidad":"1",
"id_provincia":"1"}
I want to put id_localidad at the end of the path, to generate the listview depending on the city (id_localidad is the id of the city where the shop is), not the id of the item. And this is not working for me.
Thanks in advance!
JS FILE
$('#PuntosDeVenta').live('pageshow',function(event){
var id = getUrlVars()["id"];
$.getJSON('http://localhost/CavaOnline/json_PuntosDeVentas.php?id_localidad='+id, function(vinerias) {
//THIS IS NOT WORKING, IS THE SAME AS PUTTING id, not id_localidad
$.each(vinerias, function(index, vineria) {
$('#listviewVinerias').append( '<li><a href="FichaTecnicaVineria.php?id=' + vineria[id - 1].id + '" > ' +
'<img src="pics/' + vineria[id - 1].img_url1 + '"/>' +
'<h4>' + vineria[id - 1].name+'</h4>' +
'<p>' + vineria[id - 1].street+ ' ' + vineria[id - 1].number+ '</p>' +
'</a></li>');
$('#listviewVinerias').listview('refresh')
});
});
});
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Div where I load the List
<div data-role="content">
<ul id="listviewVinerias" data-role="listview"></ul>
</div>
So I'm assuming your vinerias is a variable containing a list of JSON objects, even though I don't know why you are calling [id-1] everywhere.
If so, you can use the .filter() function to filter out the elements that have an id_localidad equal to the one specified.
var filteredVinerias = vinerias.filter(function(index){
return this["id_localidad"] === "1" //The localidad you want
});

audio tag cannot be parsed in html5 page

I link this JS page to an XML all element is views but the audio tag in xml file is not views in the html5 page ..any suggestion how to make this function retrieve the audio file and show it as html5 audi player.
init: function () {
//jQuery ajax call to retrieve the XML file
$.ajax({
type: "GET",
url: XMLLIST.xml,
dataType: "xml",
success: XMLLIST.parseXML
});
}, // end: init()
parseXML: function (xml) {
//Grab every single ITEM tags in the XML file
var data = $('item', xml).get();
//Allow user to toggle display randomly or vice versa
var list = (XMLLIST.random) ? XMLLIST.randomize(data) : data;
var i = 1;
//Loop through all the ITEMs
$(list).each(function () {
//Parse data and embed it with HTML
XMLLIST.insertHTML($(this));
//If it reached user predefined total of display item, stop the loop, job done.
if (i == XMLLIST.display) return false;
i++;
});
}, // end: parseXML()
insertHTML: function (item) {
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('image').text();
var audio=item.find('audio').text();
var title = item.find('title').text();
var desc = item.find('desc').text();
var html;
//Embed them into HTML code
html = '<div class="item">';
html += '<a href="' + url + '"><image"' + image + '" alt="' + title + '" />';
html += '<span>' + title + '</span></a>';
html += '<audio control="control"><span> ' +audio+' </span></audio>';
html += '<p>' + desc + '</p>';
html += '</div>';
//Append it to user predefined element
$(html).appendTo(XMLLIST.appendTo);
}, // end: insertHTML()
randomize: function(arr) {
//randomize the data
//Credit to JSFromHell http://jsfromhell.com/array/shuffle
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
} // end: randomize()
}
AFAIK .each() is used to iterate over a jQuery object, if you want to iterate over an array use $.each()
Here you have
$(list).each(function () {
which should be
$.each(list, function () {
since list is an array of dom nodes and not a jQuery object