I am currently trying to build an HTML form with input fields to read an XML file and write back with changes. The first step is retrieving values on page load into the input fields but it doesn't want to work
<body>
<h1>Config Page</h1>
<div>
<b>Site URL:</b> <input type="text" id="siteURL" value="site..."/></span><br>
<b>Site Collection:</b> <span id="siteCollection"></span><br>
</div>
<script>
var xmlhttp, xmlDoc;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Configuration/config.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElement
document.getElementById("siteURL").value.innerHTML =
xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue;
document.getElementById("siteCollection").innerHTML =
xmlDoc.getElementsByTagName("siteCollection")[0].childNodes[0].nodeValue;
function myFunction() {
alert(siteURL + "is the site Url")
}
</script>
<button onclick="myFunction()">Get message value</button>
I know the XML is pulling through ok because the siteCollection span item works, but the input field does not.
Any help would be much appreciated.
Thank you.
Maybe if you use jQuery you can do it as following
http://codepen.io/Daethe/pen/dXWjJo
<div>
<b>Site URL:</b> <input type="text" id="siteURL" value="site..."/></span><br>
</div>
<button onclick="myFunction()">Get message value</button>
<script>
function myFunction() {
var xmlHttp = jQuery.parseXML('<?xml version="1.0" encoding="utf-8"?><config><siteURL>http://localhost/</siteURL></config>');
var xmlDoc;
xmlDoc = xmlHttp.documentElement;
$("#siteURL").val(xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue);
}
</script>
Thanks to Daethe for putting me on the right track. I found my solution to read an xml file into a HTML input field form
for the javascript...
var xmlpath = "../configuration/test.xml"
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", xmlpath, false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;
function loadFunction() {
$("#siteURL").val(xmlDoc.getElementsByTagName("siteURL")[0].childNodes[0].nodeValue);
}
For the page...
<script src="/Script/form.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<html>
<br>Site URL (EG: http://intranet)</br>
<input type="text" id="siteURL" name="siteURL" value="blank..." />
<button onclick="loadFunction()">Load Configuration</button>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<title>Please Check Data</title>
<script type="text/javascript">
function readXMLFile() {
var i;
var xml = new XMLHttpRequest();
xml.open('GET', 'projectRelatedData.xml', false);
xml.send();
var xmlData = xml.responseXML;
xmlData=(new DOMParser()).parseFromString(xml.responseText,'text/xml');
var projectData=xmlData.getElementsByTagName("project");
//alert(projectData.length);
for(i=0;i<projectData.length;i++)
{
var name=projectData[i].getElementsByTagName("name")[0].firstChild.data;
var imageName=projectData[i].getElementsByTagName("imagePath")[0].firstChild.data;
var pdfName=projectData[i].getElementsByTagName("pdfPath")[0].firstChild.data;
var description=projectData[i].getElementsByTagName("description")[0].firstChild.data;
var amount=projectData[i].getElementsByTagName("amount")[0].firstChild.data;
//alert("number of Project : "+projectData.length);
document.write(name+'<br>');
document.write(imageName+'<br>');
document.write(pdfName+'<br>');
document.write(description+'<br>');
document.write(amount+'<br>');
}
}
</script>
</head>
<body>
<button onclick="readXMLFile()">Click</button>
<p id="ccc"></p>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<projectWebsite>
<project>
<name>CARGO SHIPPING</name>
<imagePath>CARGOSHIPPING.PNG</imagePath>
<pdfPath>cargoShipping.pdf</pdfPath>
<description>
Cargo shipping is all about booking cargo to move from one place to another. Owner can add new shipsand he can also track ships.User can register for cargo and he can also track ships.Admin has the right to view detailsof owner, to add a new company and also update price of ship. This software hasa very nice GUI to give a very nice presentation of a cargo management system.
</description>
<amount>4000</amount>
</project>
<project>
<name>E-BAZZAR</name>
<imagePath>ebazzar.PNG</imagePath>
<pdfPath>eBazar.pdf</pdfPath>
<description>
This project emphasizes on taking bookings of pat ient in a web portal system.Patient can search for the doctor and book for appointment . Doctor can check and confirm appointment so patient can visit accordingly.Also admin is provided to add doctors in the portal,moreover customer list can be seen as well.
</description>
<amount>4000</amount>
</project>
</projectWebsite>
Related
I want to getElementsByTagName in xml file.
It is my code(.html).
<html>
<header>
<title>Read XML</title>
</header>
<body>
<h1>Hello My Application</h1>
<script type="text/javascript">
function readXML()
{
var xml= new XMLHttpRequest();
xml.open('GET', 'C:\Users\xxx\Testxml.xml');
//xml.send();
var xmlData = xml.responseText;
if(!xmlData)
{
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
var emp = xmlData.getElementsByTagName("employee");
var name= emp[0].getElementsByTagName("name")[0].firstChild.data;
document.write("Name = " + name);
}
}
</script>
<button onclick="readXML()">Read XML File</button>
</body>
</html>
I run filename.html but there is error on line var name= emp[0].getElementsByTagName("name")[0].firstChild.data;
It is my xml file.
<company>
<employee>
<name>Chrish</name>
<age>40</age>
<salary>100</salary>
</employee>
</company>
Could you help me please?
Have you tried logging your xmlData variable to see if you are actually able to read the xml file? Because, as far as I know, reading local xml files in javascript is not allowed directly. You can try reading it through the File API. Read more about it here.
And secondly, your if condition seems incorrect. You are checking for (!xmlData) which means it will run when xmlData is empty while it should be running when you are actually able to get data in xmlData variable.
I have a html code that is supposed to create a xmlDoc object, read an XML code into it from a file, get a value of a node and print it on screen. However, the code below is executed but does not read the value. What I get is just empty string I guess. I tried .firstChild and the result was the same:
<text> is :)
Between "<text> and "is :)" I'd expect "My child no 1.". Thanks for any help.
The html code:
<!DOCTYPE html>
<html>
<head>
<title>Test html</title>
<script src="loadxmldoc.js"></script>
</head>
<body>
<script>
var xmlDoc = loadXMLDoc("test_xml.xml");
var x = xmlDoc.getElementsByTagName("child")[0].childNodes[0];
var txt = x.nodeValue;
document.write("<txt> is " + txt + " :)");
</script>
</body>
</html>
XML test_xml.xml code:
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<children>
<child id="1">
<txt>My child no 1.</txt>
</child>
<child id="2">
<txt>My child no 2.</txt>
</child>
<child id="3">
<txt>My child no 3.</txt>
</child>
<child id="4">
<txt>My child no 4.</txt>
</child>
</children>
</root>
and loadXMLDoc function in loadxmldoc.js file:
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else { // code for IE5 and IE6
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
It is not the full answer to my question but the problem is partially resolved. The code below works but I've got to use getElementsByTagName function to get to html tags which I wanted to avoid and use firstChild, for instance. Anyway this is what works.
<!DOCTYPE html>
<html>
<head>
<title>Test html</title>
<script src="loadxmldoc.js"></script>
</head>
<body>
<script>
var xmlDoc = loadXMLDoc("test_xml.xml");
var children = xmlDoc.getElementsByTagName("children")[0];
var childn = children.getElementsByTagName("child")[0];
var x = childn.getElementsByTagName("txt")[0];
document.write("<txt> is " + x.firstChild.nodeValue + " :)");
</script>
</body>
</html>
I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.
<html>
<head>
<title>textbox</title>
<script type="text/javascript">
function readBOX() {
var txtinput = document.getElementById('txtinput').value;
document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
}
</script>
</head>
<body>
<p> Type</p>
<input type="text" id="txtinput" />
<input id="open" type="button" value="READ" onClick="readBOX()" />
<form>
<textarea name="text" rows="20" cols="70">loaded text here</textarea>
</form>
</body>
</html>
You have to use something like its posted in this Answer
jQuery
$(document).ready(function() {
$("#open").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$("#text").text(data);
}
});
});
});
Read more on the jQuery Documentation of .ajax()
Non jQuery
I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia
Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object
Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.
<!DOCTYPE HTML>
<html>
<head>
<title>textbox</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
Process.php
<textarea name="text" rows="20" cols="70">
<?php $name = $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
This is how I load text into a textarea
Main.css
.textbox{
font-size: 12px;
float : left;
height : 197px;
width : 650px; }
Default.html
<!DOCTYPE html>
<html>
<head>
<!-- Charactor set allowed to use -->
<meta charset="utf-8"/>
<title>Text from .txt file to TextArea</title>
<!-- External stylesheet -->
<link rel="stylesheet" href="main.css" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<textarea class="textbox" id="Brief" readonly></textarea>
<script> $( "#Brief" ).load( "text.txt" ); </script>
</body>
</html>
google textarea to find format of text area
One of the easiest way is to request the server to return the pre-filled textarea
(Here's an example using PHP):
<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>
Note: Something similar can be done with any server-side scripting language.
In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.
Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):
Pure JS:
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
}
function readBOX() {
function reqListener () {
document.forms[0].text.value = this.responseText;
}
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", filePath, true);
oReq.send();
}
But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:
jQuery:
function readBOX() {
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
$.ajax({
url: filePath
}).done(function(data){
document.forms[0].text.value = data;
});
}
Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.
Hope this helps :)
window.addEventListener('DOMContentLoaded', (e) => {
let input = document.getElementById('input');
// load default.txt into input box
try {
let fileToLoad = './default.txt';
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', fileToLoad, false);
xmlhttp.send();
input.innerHTML = xmlhttp.responseText;
} catch(DOMException) {
input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
}
});
Im trying to parse an xml string in IE based on the following example: http://dean.edwards.name/weblog/2006/04/easy-xml/
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function(){
var xml = document.createElement("xml");
xml.src = '<test><node1>Test</node1></test>';
document.body.appendChild(xml);
var xmlDocument = xml.XMLDocument;
document.body.removeChild(xml);
});
</script>
</head>
<body>
</body>
</html>
Fiddle
However, its not working. I get no errors, but nothing is happening.
Is there any way to generate an XML file on the client side in IE based on a valid xml string? Is activeX the only option?
Thanks in advance
A variant I have working is not to create an xml object, but create a wrapper div instead:
<script type="text/javascript">
$(function(){
var div, xmlDocument;
div = document.createElement('div');
div.innerHTML = '<xml><test><node1>Test</node1></test></xml>';
document.body.appendChild(div);
xmlDocument = div.firstChild.XMLDocument;
document.body.removeChild(div);
});
</script>
ActiveX is certainly one option. The code would be something like:
var xml = '<test><node1>Test</node1></test>';
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xml);
alert(xmlDoc.documentElement.nodeName);
I am trying to use Java-script as a client for java based restful web-service. The service is a survey maker. I am having trouble getting the function to work. The server side of the service is in Google App Engine. In the code below the function uses http get to get xml representing a list of surveynames, then gets the data from the xml and puts it in a html table. The code is not working, so it would be great if some one could check it to see if I am doing this correctly or I am doing something wrong. I have never programed in javascript so I would also like to know if I need to import a library to use AJAX or is it supported by the browser?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>View Surveys</title>
</head>
<SCRIPT>
function getSurveyNames(){
var url = "http://survey-creator.appspot.com/rest/surveymakerpro/allsurveys";
var xmlhttp;
// AJAX code for Mozilla, Safari, Opera etc.
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = xmlhttpChange;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
// AJAX code for IE
else
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
xmlhttp.onreadystatechange = xmlhttpChange;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
HTMLSurveyNames = "<table border='1'><tr>Survey Names<th></th></tr>";
var surveyNames = xmlhttp.responseXML.documentElement.getElementsByTagName("surveys")[0];
for(var i = 0; i < surveyNames.length ;i++){
var surveyNameChildNode = surveyName[i].childNodes[0];
var name = surveyNameChildNode.nodeValue;
HTMLSurveyNames += "<tr><td>"+name+"</td></tr>";
}
//div tags
document.getElementById('displayNames').innerHTML = HTMLSurveyNames;
}
}
</SCRIPT>
<body>
<p>View Survey</p>
<form method="post">
<input name="GetSurveys" style="width: 103px" type="button" value="View all surveys" onClick=getSurveyNames(); /></form>
<p>Here Goes a Table of Surveys</p>
<div id="displayNames">
<p>Enter the survey you wish to take:</p>
<form method="post">
<input id="surveyName" name="SurveyName" style="width: 140px" type="text" value="Enter Survey Name...." /></form>
<form method="post">
<input name="Submit2" type="submit" value="Get Survey" /></form>
<div id="displaySurvey"></div>
</div>
<p>
<input id="sendtoserver" name="Submit3" type="submit" value="Submit TakenSurvey" /></p>
</body>
</html>
This is the xml I want to parse
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><surveyNames><SurveyList><surveys>DragonBallZ</surveys><surveys>FootballSurvey</surveys><surveys>NewsSurvey</surveys><surveys>PennstateSurvey</surveys></SurveyList></surveyNames>
You're sending off an asynchronous request, but then attempting to immediately process the result before this request will have finished.
You should assign a handler to xmlhttp.onreadystatechange that will be executed as your request progresses. You currently assign xmlhttpChange to this property, but you don't show what xmlhttpChange is. You should be doing something like this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// XML parsing code goes here
}
}
You do not need to import any libraries to use Ajax
Be careful with lines like HTMLSurveyNames = "<table border='1'><tr>Survey Names<th></th></tr>"; You should always use the var keyword when declaring variables, to avoid creating/modifying globals implicitly.
"<table border='1'><tr>Survey Names<th></th></tr>"
should be
"<table border='1'><tr><th>Survey Names</th></tr>"
things will work a LOT better.
there is a cross-browser XML librari for javascript at http://www.softxml.com/softxmllib/softxmllib.htm
I believe XMLHTTPRequest() is specific to IE. there are versions for other browsers. http://en.wikipedia.org/wiki/XMLHttpRequest