Read the xml in javascript - javascript

I have this type of xml
<root>
<Message code="AC_CONNECTOR__FAIL_IN_CONNECT"
id="AR_AC_CONNECTOR__FAIL_IN_CONNECT"
bundleName="Error" locale="pt" severity="4" userFlag="">
(AR1-000001) Error in the data
</Message>
<Message code="AC_CONNECTOR__FAIL_IN_DISCONNECT"
id="AR_AC_CONNECTOR__FAIL_IN_DISCONNECT" bundleName="Error"
locale="pt" severity="4" userFlag="">
(AR1-000001) error
</Message>
</root>
and i want it to be read in the javascript
after reading this i need to replace value of the message with another based on the code property of the message
i have done this code ...
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reading XML</title>
<script type="text/javascript">
function readXML() {
var xml = new XMLHttpRequest();
xml.open('GET', 'error1.xml', false);
xml.send();
var xmldata = xml.responseXML;
document.write("Nutan");
xmldata = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
var emp = xmldata.getElementsByTagName("ptr");
// document.write(emp);
var output=emp[0].getElementsByTagName("Message")[0].firstChild.data;
document.write(output);
}
</script>
</head>
<body>
<h1>
XMl file
</h1>
<button onclick="readXML()">Read xml file</button>
</body>
</html>
but this code is not reading the xml file ..which is in above format
please help me to read xml file with above format

If you want to access the code value you have to use the getAttribute("code") function reference, if you want to list the code value for each child the following code is working.
<html>
<head>
<script>
function readXML() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "error1.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("Message");
for (var i = 0; i < x.length; i++) {
var node_code = x[i].getAttribute("code");
document.write(node_code + " ");
var node_value = x[i].childNodes[0].nodeValue;
document.write(node_value + " <br>");
}
}
</script>
</head>
<body>
<button onclick="readXML()">Read xml file</button>
</body>
</html>
It's better if you separate your JS code from your HTML by using two separate files. If this isn't what you are looking for please explain your problem better.

Related

include html in other html with a .js attached

I have this simple html:
<head>
<h1>Prueba</h1>
</head>
<body>
<form method="POST" action="">
Introduce KeyWord <input type="text" name="key">
<input type="submit" name="submit" value="Submit">
</form>
</body>
Now, i want to include inside other html which has severak .js attached. I have seen different ways but i only get include only the file html, without the .js attached.
Any help? Thank you so much!
Edit: This is the other html that i want include inside, with the js attached:
<html>
<head>
<meta charset="UTF-8">
<title>Word Cloud</title>
<script src="d3.js" charset="utf-8"></script>
<script src="d3.layout.cloud.js"></script>
<script src="d3.wordcloud.js"></script>
<script src="example.words.js"></script>
</head>
<body style="text-align: center">
<h1>Word Cloud</h1>
<div id='wordcloud'></div>
</body>
</html>
Demo Link : https://plnkr.co/edit/kByh82pSAw6sQAOFp5gO?p=preview
you can include html file using this javascript function:
javascript: and html code:
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
includeHTML();
<!DOCTYPE html>
<html>
<body>
<div w3-include-html="<**html-name-file**>"></div>
</body>
</html>
i found this code there
You can make use of an iframe to embed another website into yours like so:
<iframe src="other.html" height="200" width="300"></iframe>
In this case other.html contained links to other pages in the website and links to js files.
Demo Link: https://plnkr.co/edit/kByh82pSAw6sQAOFp5gO?p=preview
This one is working absolutely fine.
Keep one thing in mind that if you will test on your PC it will not work directly. You will get an error in your console Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https..
So, do test on the server I mean localhost
Happy Coding
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("data-include");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
// Get the DOMPareser to parse String into HTML
var parser = new DOMParser();
var doc = parser.parseFromString(this.responseText, "text/html");;
elmnt.innerHTML = this.response ;
var allscripts = doc.getElementsByTagName('script');
// Run all the Javascript
for(var k = 0; k<allscripts.length;k++){
var x = allscripts[k].innerHTML;
eval(x);
}
}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("data-include");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div data-include="text.html"></div>
<script>
includeHTML();
</script>
</body>
</html>

is it possible to display an image from a xml file using DOM?

I'm new to this forum and I want to ask a question on how can I make an image from an xml file to load itself using DOM? here is my code and I don't know what's wrong in it. Can anyone help me debug this please? thanks :)
<html>
<head>
<script language="javascript" type="text/javascript">
function showImage(){
var xmlimg = document.getElementById("myphoto");
var photo=xmlimg.getElementsByTagName("photo");
var showImg =document.createElement("div");
showImg.createElement("IMG");
showImg.setAttribute("src","sunset.jpg");
var getImage=document.createElement("div");
getImage.setAttribute("class","fileko");
showImg.appendChild(getImage);
var viewimage= document.createTextNode(photo.getElementsByTagName("fileko")[0].firstChild.data);
getImage.appendChild(viewimage);
getImage.appendChild(viewimage);
var getAttr=document.createElement("div");
getAttr.getAttribute("stolen");
showImg.appendChild(getAttr);
document.getElementsByTagName("body")[0].appendChild(showImg);
}
</script>
</head>
<body onload="showimage()" style="display:none">
<xml id="myphoto" >
<photo kind="stolen">
<fileko>sunset.jpg</fileko>
<desc>Sunrise</desc>
</photo>
</xml>
</body>
</html>
You can do an Ajax request to the xml file and get the data needed. Then create an Image element with the proper properties based on retrieved data and then append that image element into the DOM.
yes it is possible just follow below code and you will get that easily what you need to do. this is my code that is fetching data from xml file
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
my xml look like this
xml file

Displaying Order History without using tables

i am new to UI devlopment.I use to do coding but i have been asked to get the value from xml and display order history without using tables.I am getting xml from jax-rs and want to display on html.
My Xml is:
<orderHistory>
<orders>
<description>Electronic order</description>
<detail_url>
http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039011
</detail_url>
<lineItemCount>ssolineItemCount</lineItemCount>
<order_id>7039012</order_id>
<sort_date>1448316</sort_date>
<status>Shipped</status>
<store_label>SSO Store</store_label>
<submitted_date>11/19/2015</submitted_date>
<total>11.76</total>
<tracking_href>www.abc.com</tracking_href>
<tracking_num>1234</tracking_num>
</orders>
<orders>
<description>Electronic order</description>
<detail_url>
http://shop.scholastic.com/webapp/wcs/stores/servlet/MyAcctItemHistoryView?langId=-1&storeId=10751&orderId=7039009
</detail_url>
<lineItemCount>tsolineItemCount</lineItemCount>
<order_id>7039009</order_id>
<sort_date>1448316</sort_date>
<status>Cancelled</status>
<store_label>Teacher Store</store_label>
<submitted_date>11/19/2015</submitted_date>
<total>15.25</total>
<tracking_href>www.abc.com</tracking_href>
<tracking_num>1234</tracking_num>
</orders>
<orderHistory>
My Html is like:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="javascript">
var xmlhttp;
function init() {
// put more code here in case you are concerned about browsers that do not provide XMLHttpRequest object directly
//xmlhttp = new XMLHttpRequest();
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function getdetails() {
var empno = document.getElementById("empno");
var url = "http://localhost:8080/NewShot/schl-api/myresource/com/";
xmlhttp.open('GET', url, false);
xmlhttp.send();
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
//alert('Inside');
var xmlData = xmlhttp.responseXML;
if (!xmlData) {
xmlData = (new DOMParser())
.parseFromString(
xmlhttp.responseText,
'text/xml');
}
// alert('Content'+xmlData);
var store , O_url ,status,total,description,tracknum,litncount,trackhrf,subdate,sdate,durl,elements;
var conference = xmlData
.getElementsByTagName("orders");
for (var i = 0; i< conference.length; i++) {
// alert('In For');
store = conference[i].getElementsByTagName("store_label")[0].firstChild.data;
O_url = conference[i].getElementsByTagName("order_id")[0].firstChild.data;
status = conference[i].getElementsByTagName("status")[0].firstChild.data;
total = conference[i].getElementsByTagName("total")[0].firstChild.data;
description = conference[i].getElementsByTagName("description")[0].firstChild.data;
tracknum = conference[i].getElementsByTagName("tracking_num")[0].firstChild.data;
litncount = conference[i].getElementsByTagName("lineItemCount")[0].firstChild.data;
trackhrf = conference[i].getElementsByTagName("tracking_href")[0].firstChild.data;
subdate = conference[i].getElementsByTagName("submitted_date")[0].firstChild.data;
sdate = conference[i].getElementsByTagName("sort_date")[0].firstChild.data;
durl = conference[i].getElementsByTagName("detail_url")[0].firstChild.data;
//alert(date+" "+name+" "+url);
elements +="StoreType::"+store+ "<br>" +"OrderUr::"+ O_url + "<br>" +
"Status::"+status+"<br>"+"Total Bill::"+total+"<br>"+""+"Item Description::"+description+"<br>"+"Trackinh Number::"+tracknum+"<br>"+
"LineItemCount::"+litncount+"<br>"+"Tracking Link::"+trackhrf+"<br>"+"Submission Date::"+subdate+"<br>"+"Sort Date::"+sdate+"<br>"+"DetailUrl::"+durl+"<br><br>";
}
document.getElementById("demo").innerHTML= elements;
/* date = conference[0]
.getElementsByTagName("date")[0].firstChild.data;
name = conference[0]
.getElementsByTagName("name")[0].firstChild.data;
url = conference[0]
.getElementsByTagName("url")[0].firstChild.data;
*/
// alert('Name'+name+'Date'+date+'url'+url);
} else {
name = "";
date = "";
url = ""
alert("Invalid Employee ID");
}
} else {
alert("Error ->" + xmlhttp.responseText);
}
}
</script>
</head>
<body onload="init()">
<h1>Call Scholastic Service </h1>
<table>
<tr>
<input type="button" value="Get Details" onclick="getdetails()"/>
</tr>
</table>
<p id="demo"></p>
</body>
</html>
I want to display value without using table in following format:
Store Label: <Value> LineItem Count:<Value>
OrderId: <Value> LineItem Count:<Value>
Status Times: <Value> Tracking Link:<Value>
Total: <Value> Submission Date:<Value>
Description: <Value> Date Sorting:<Value>
Tracking Number:<Value>
Detail Url:<Value>
I tried using but it was not proper.
Thanks

How can I parse a text file using javascript

The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request

Showing the output of a JSON request

JSON URL : http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&suggest=
Here "str" may be any 2-3 char for an example
str = 'nas'
then JSON URL : http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search=nas&namespace=0&suggest=
I want to grab all result and put these result in a table
I tried AJAX, JSON, JQUERY
Can any one send me working Code for doing this .
My Dummy Code as :-
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
function FillSearchBox(str)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status=200)
{
//Pointer never Comes in this Section (If I Debuug I got xmlhttp.status=0 every time)
var JSONObject = JSON.parse(xmlhttp.responseText);
}
}
var strr= "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&suggest=";
xmlhttp.open("GET",strr,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" name="wikisearch" id="" onkeyup="FillSearchBox(this.value)" />
</form>
<!-- add Table or Div Here -->
</body>
</html>
You need to use JSONP to make cross-origin requests:
function gotData(d) { alert(d); }
var s = document.createElement('script');
s.src = "http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search="+str+"&namespace=0&callback=gotData";
s.appendTo(document.body);
Note that this is much easier with jQuery.

Categories