xml parsing from url in javascript - javascript

I need some code for parsing XML from a url in javascript. I tried following code:
Source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<head><title>Employee Data</title>
<script>
// This function loads the XML document from the specified URL, and when
// it is fully loaded, passes that document and the url to the specified
// handler function. This function works with any XML document
function loadXML(url, handler) {
// Use the standard DOM Level 2 technique, if it is supported
if (document.implementation && document.implementation.createDocument) {
// Create a new Document object
var xmldoc = document.implementation.createDocument("", "", null);
// Specify what should happen when it finishes loading
xmldoc.onload = function() { handler(xmldoc, url); }
// And tell it what URL to load
xmldoc.load(url);
}
// Otherwise use Microsoft's proprietary API for Internet Explorer
else if (window.ActiveXObject) {
var xmldoc = new ActiveXObject("Microsoft.XMLDOM"); // Create doc.
xmldoc.onreadystatechange = function() { // Specify onload
if (xmldoc.readyState == 4) handler(xmldoc, url);
}
xmldoc.load(url); // Start loading!
}
}
// This function builds an HTML table of employees from data it reads from
// the XML document it is passed.
function makeTable(xmldoc, url) {
// Create a <table> object and insert it into the document.
var table = document.createElement("table");
table.setAttribute("border", "1");
document.body.appendChild(table);
// Use convenience methods of HTMLTableElement and related interfaces
// to define a table caption and a header that gives a name to each column.
var caption = "Employee Data from " + url;
table.createCaption().appendChild(document.createTextNode(caption));
var header = table.createTHead();
var headerrow = header.insertRow(0);
headerrow.insertCell(0).appendChild(document.createTextNode("Name"));
headerrow.insertCell(1).appendChild(document.createTextNode("Address"));
headerrow.insertCell(2).appendChild(document.createTextNode("State"));
// Now find all <employee> elements in our xmldoc document
var employees = xmldoc.getElementsByTagName("item");
// Loop through these employee elements
for(var i = 0; i < employees.length; i++) {
// For each employee, get name, job, and salary data using standard DOM
// methods. The name comes from an attribute. The other values are
// in Text nodes within <job> and <salary> tags.
var e = employees[i];
var name = e.getAttribute("name");
var job = e.getElementsByTagName("address")[0].firstChild.data;
var salary = e.getElementsByTagName("state")[0].firstChild.data;
alert(name);
// Now that we have the employee data, use methods of the table to
// create a new row and then use the methods of the row to create
// new cells containing the data as text nodes.
var row = table.insertRow(i+1);
row.insertCell(0).appendChild(document.createTextNode(name));
row.insertCell(1).appendChild(document.createTextNode(job));
row.insertCell(2).appendChild(document.createTextNode(salary));
}
}
</script>
</head>
<!--
The body of the document contains no static text; everything is dynamically
generated by the makeTable() function above.
The onload event handler starts things off by calling loadXML() to load the XML data file. Note the use of location.search to encode the name of the xml file in the query string. Load this HTML file with a URL like this: DisplayEmployeeData.html?data.xml
-->
<body onload="loadXML(url, makeTable)">
</body>
</html>

Related

SuiteScript Create File In Client Side Script

I'm trying to create a file in the File Cabinet and write to it in a Client Script. Checking the API reference, I see that all the File objects are Server-side only.
Does that mean you can't create and write to a file in a Client script? I tried to use the code in my Client script anyway, but got the error:
Fail to evaluate script: {"type":"error.SuiteScriptModuleLoaderError","name":"{stack=[Ljava.lang.Object;#59c89ae9, toJSON=org.mozilla.javascript.InterpretedFunction#5a4dd71f, name=MODULE_DOES_NOT_EXIST, toString=org.mozilla.javascript.InterpretedFunction#1818dc3c, id=, message=Module does not exist: N/file.js, TYPE=error.SuiteScriptModuleLoaderError}","message":"","stack":[]}
When I tried to save it in NetSuite as the script file. Does the above mean that the N/File object can't be loaded in a Client script?
Can I write to a file in a Client script?
Create a Client Script - this Script will contain the function to call the Suitelet and pass along information from the current record/session if needed.
function pageInit{
//required but can be empty
}
function CallforSuitelet(){
var record = currentRecord.get();
var recId = record.id;
var recType = record.type
var suiteletURL = url.resolveScript({
scriptId:'customscriptcase3783737_suitelet',// script ID of your Suitelet
deploymentId: 'customdeploycase3783737_suitelet_dep',//deployment ID of your Suitelet
params: {
'recId':recId,
'recType':recType
}
});
document.location=suiteletURL;
}
return {
CallforSuitelet : CallforSuitelet,
pageInit : pageInit
}
Create a Suitelet - this script will create the file
function onRequest(context) {
var requestparam = context.request.parameters;
var recId = requestparam.recId; //the same name of the fields specified in url.resolveScript parameters from Client Script
var recType = requestparam.recType;
var objRecord = record.load({
type: record.Type.___,//insert record type
id: recId
});
var content = 'Insert Content Here';
var xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//report\" \"report-1.1.dtd\">\n";
xml += "<pdf>\n<body font-size=\"12\">\n<h3>Sample PDF</h3>\n";
xml += "<p></p>";
xml += content;
xml += "</body>\n</pdf>";
context.response.renderPdf({xmlString: xml});
}
return {
onRequest: onRequest
}
As you've already discovered, server-only modules can't be called from client-side scripts directly, but this can be done via a Suitelet. You will need to decide how the Suitelet does it's work. An example of the principal at work can be found here and here

Having trouble loading HTML table from XML doc

I am having trouble loading values from an XML file and inserting them into a HTML table. It says that the html tag I am attempting to access is undefined "script.js:15 Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefined". I am trying to insert the values of and into a html table from the loaded XML file.
// script.js
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "table.xml", true);
xmlhttp.send();
}
function myFunction() {
var xmlDoc = XMLHttpRequest.responseXML;
var table = '<tr><th>Name</th><th>Age</th></tr>';
var x = xmlDoc.getElementsByTagName('STUDENT');
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("AGE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("students") = table;
}
//relevant html
<body>
<br><br>
<table id="students"></table>
<script src="script.js"></script>
</body>
//XML Doc Contents
<CLASS ID=”Advanced Web Development”>
<STUDENT>
<NAME>Tom</NAME>
<AGE>19</AGE>
<HEIGHT>1.3</HEIGHT>
<SEX>M</SEX>
<GRADE>B</GRADE>
</STUDENT>
<STUDENT>
<NAME>Dick</NAME>
<AGE>29</AGE>
<HEIGHT>1.1</HEIGHT>
<SEX>M</SEX>
<GRADE>A</GRADE>
</STUDENT>
<STUDENT>
<NAME>Harry</NAME>
<AGE>39</AGE>
<HEIGHT>1.5</HEIGHT>
<SEX>M</SEX>
<GRADE>C</GRADE>
</STUDENT>
<STUDENT>
<NAME>Mary</NAME>
<AGE>30</AGE>
<HEIGHT>1.1</HEIGHT>
<SEX>F</SEX>
<GRADE>B+</GRADE>
</STUDENT>
</CLASS>
There appears to be a few things you aren't quite doing right here:
Firstly, the XMLHttpRequest class doesn't have a responseXML property: that isn't where to get the result of an asynchronous request. Instead, the responseXML property belongs to the individual XMLHttpRequest objects (or 'instances'). You create a new XMLHttpRequest instance in the variable xmlhttp in the line var xmlhttp = new XMLHttpRequest();, and it will be xmlhttp that contains the responseXML property.
Additionally, you are passing the value of this in your onreadystatechange handler to myFunction, but myFunction doesn't take any arguments. JavaScript has very lax restrictions on calling functions with the correct number of arguments: any surplus arguments are simply ignored.
Try changing the first couple of lines of this function from
function myFunction() {
var xmlDoc = XMLHttpRequest.responseXML;
to
function myFunction(result) {
var xmlDoc = result.responseXML;
This allows myFunction to receive the xmlhttp instance and pull the response XML out of it.
Secondly, at the end of the function you write:
document.getElementById("students") = table;
Your variable table contains an HTML string representing the contents of a table. However, you can't set an element to an HTML string. What you instead want to do is to assign this HTML string to the inner HTML of this element, using the innerHTML property of the element:
document.getElementById("students").innerHTML = table;
Finally, the XML document you include in your question isn't well-formed, in that the ID attribute of the root element uses smart quotes (”) to surround the value when it should use neutral quotes (") instead. If the XML isn't well-formed, the responseXML property of result will be null.
I made these changes to your code and it worked, in that I could load up the XML and have the table filled out with the data in the XML file.

Access <link> value in XML with Javascript

I'm using Ajax/jQuery to pull in some content from an RSS feed, but it seems to be failing to read the content of an XML node with the name 'link'.
Here's a simplified version of the XML:
<?xml version="1.0" encoding="UTF-8"?>
<channel>
<item>
<title>Title one</title>
<link>https://example.com/</link>
<pubDate>Mon, 12 Feb 2019</pubDate>
</item>
<item>...</item>
<item>...</item>
</channel>
</xml>
And the code I'm using:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('item', this.responseText).each(function(){
var thisPostData = {};
thisPostData.title = $(this).find('title').text();
thisPostData.link = $(this).find('link').text();
thisPostData.date = $(this).find('pubDate').text();
posts.push(thisPostData);
});
console.log(posts);
}
};
var posts = [];
xhttp.open('GET', 'https://example.com/rssfeed/', true);
xhttp.send();
You'll see I'm trying to add each 'item' to an object, and storing them inside the 'posts' array. 'Title' and 'pubDate' are stored fine but 'link' isn't.
The actual RSS feed in question contains a huge amount of extra data, all of which I can read except the 'link' nodes. Any suggestions why nodes called 'link' would act differently from all the others?
The problem is because you're attempting to parse XML as HTML. The <link> object in HTML is an inline element, not a block level one, so it has no textContent property for jQuery to read, hence the output is empty.
To fix this first read the XML using $.parseXML(), then put it in a jQuery object which you can traverse.
There's also a couple of things to note. Firstly you will need to remove the </xml> node at the end of the XML output as it's invalid and will cause an error when run through $.parseXML. Secondly you can use map() to build an array instead of manually calling push() on an array, and you can just return the object definition directly from that. Try this:
var responseText = '<?xml version="1.0" encoding="UTF-8"?><channel><item><title>Title one</title><link>https://example.com/</link><pubDate>Mon, 12 Feb 2019</pubDate></item><item><title>Title two</title><link>https://foo.com/</link><pubDate>Tue, 13 Feb 2019</pubDate></item></channel>';
var xmlDoc = $.parseXML(responseText)
var posts = $('item', xmlDoc).map(function() {
var $item = $(this);
return {
title: $item.find('title').text(),
link: $item.find('link').text(),
date: $item.find('pubDate').text()
};
}).get();
console.log(posts);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Lastly, you're using a rather odd mix of JS and jQuery. I'd suggest going with one or the other. As such, here's a full jQuery implementation with the AJAX request included too:
$.ajax({
url: 'https://example.com/rssfeed/',
success: function(responseText) {
var xmlDoc = $.parseXML(responseText)
var posts = $('item', xmlDoc).map(function() {
var $item = $(this);
return {
title: $item.find('title').text(),
link: $item.find('link').text(),
date: $item.find('pubDate').text()
};
}).get();
// work with posts here...
}
});

Apply JS onto table, which is created after page is loaded

I have got an html page, where you can put text into a textarea, click a button and then it creates an html table.
Problem is, that i am using a JS file to make my table sortable, but this JS file is not applied to tables that are created after the page itself is created.
How can i call the JS file again after the button is clicked and the table created? Or is there any other way to apply the JS file to the new table?
My problem seems to be like this problem:
Apply jquery propieties on new element created after the page is loaded
But i can't use JQuery, is there any way without it?
Example for a created table:
<div id="artikelnr2">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="table.css">
<script src="java.js"></script>
<div class="datagrid"><table class="sortable">
<thead><tr><th>Nummer</th><th>Nummer</th><th>Bezeichnung</th><th>Bemerkungen</th></tr></thead>
<tbody>
<tr><td>897-251</td><td>00.702.07803.7</td><td>5G2</td><td>-</td></tr><tr><td>897-1051</td><td>00.702.0306.7</td><td>5G1</td><td>-</td></tr><tr><td>897-1651</td><td>00.702.0307.3</td><td>5G1U</td><td>-</td></tr><tr><td>897-341</td><td>00.702.0323.9</td><td>5G2.5</td><td>-</td></tr>
</tbody>
</table></div>
</div>
I am using sorttable.js from this page:
http://www.kryogenix.org/code/browser/sorttable/
JavaScript which is called after button is clicked (pastes the content of another page into an exisiting div container):
function getOutput(url) {
var file = selectedValue()+".csv";
var value = document.getElementById("artikelnr").value;
<!---Leerzeichen entfernen-->
value = myTrim(value);
var url = url || "verarbeitung.php?eingabe="+value+"&eingabe2="+file ;
getRequest(
url, // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('artikelnr2');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('artikelnr2');
container.innerHTML = responseText;
tempResult = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
So this is a suggestion as a major part of your code is not available.
In your existing code, where you create the new table, you need to add/run the following:
sorttable.makeSortable(newTableObject);
The newTableObject reference you either can get straight from your existing code or by calling document.getElementById(idOfTheTableIJustAdded) after your added the new table to the DOM.
Src: http://www.kryogenix.org/code/browser/sorttable/
Update after question edit:
In this script function you should be able to do like this
function drawOutput(responseText) {
var container = document.getElementById('artikelnr2');
container.innerHTML = responseText;
//tempResult = responseText;
var newTableObject = container.querySelector(".sortable");
sorttable.makeSortable(newTableObject);
}

Using window.open, document.open, and document.write to display XML (XML rendering gone)

This is related to another question, but is not a duplicate.
It deals with a proposed solution that I have reached an impasse.
I have the following code that reads an XML, makes changes, opens a window, and writes the XML into the document. The problem is that the content is not rendered as XML.
Any way to set a content type, etc, to have the browser handle the content as XML?
<script>
var wxml;
var xDoc;
var xDevices, xInputs;
var xDevice, xInput;
function fSetXmlAInput(iDevice, iNode, nodeNewVal) {
xInput = xInputs[iNode];
xValue = xInput.getElementsByTagName("value")[0];
// change node value:
// console.log("nodeVal: " + xValue.firstChild.nodeValue);
xValue.firstChild.nodeValue = nodeNewVal;
// console.log("newVal: " + xValue.firstChild.nodeValue);
}
function fSetXmlDevice(iDevice) {
xDevice = xDevices[iDevice];
xInputs = xDevice.getElementsByTagName("input");
fSetXmlAInput(iDevice, 0, "22");
fSetXmlAInput(iDevice, 1, "33");
}
function alternativeLoadXML3() {
// load xml file
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // IE 5/6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "my_template.xml", false);
xhttp.send();
xDoc = xhttp.responseXML;
xDevices = xDoc.getElementsByTagName("device");
fSetXmlDevice(1);
var xmlText = serializeXmlNode(xDoc);
var newWindow = window.open("my_template.xml", "Test", "width=300,height=300,scrollbars=1,resizable=1");
newWindow.document.open();
newWindow.document.write(xmlText);
newWindow.document.close()
};
</script>
Below the XML as well:
<?xml version="1.0" encoding="utf-8"?>
<myXmlRoot>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
<device>
<input><name>"name 1"</name><value>{replaceMe!}</value></input>
<input><name>"name 2"</name><value>{replaceMe!}</value></input>
</device>
</myXmlRoot>
Any way to force the browser to render content in new window as XML...or does using document.open and document.write mean code is rendered as HTML?
Related: Change XML content using JavaScript, missing refresh
Use dataURI to write xml into new window is very easy.
window.open('data:text/xml,'+encodeURIComponent(xmlText),
"Test", "width=300,height=300,scrollbars=1,resizable=1");
Both document.open and document.write are used to write HTML or Javascript to a document. This goes back to the DOM Level 2 Specification of document.open, which assumes that the document is opened in order to write unparsed HTML.
Instead of using document.open and document.write, I would instead suggest dymanically adding elements using the XML DOM as in sampleElement.appendChild(XMLnode)
A similar question can also be found here: how to display xml in javascript?

Categories

Resources