Loading an XML document onclick - javascript

I am attempting to write this code so when I click on the XML button it will show my XML document. I am unable to get the button to do anything, I am assuming that the function is missing something. Any help would be appreciated. Thanks in advance.
Function
<script language = "JavaScript">
xmlOpen = function(){
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","gameXML.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
}
</script>
Button HTML
<p>
<label>List of users:</label>
<input type="button" value="XML" id="users" onclick="xmlOpen()">
</p>

Are you serving these files from a web server? OR are you just opening the HTML page from your file system? If you use Chrome and try to open the HTML file from your file system, you will get an error (see the console) when you click the "XML" button.
To get around this, you can either serve the files from a web server (even on your local machine) OR you could try opening the HTML page in Firefox.
In terms of displaying the contents of the XML file, try taking a look at this question: How do I loop through XML Nodes in JavaScript?
Update:
I was successful in testing with the code below. Opening the HTML file from my Desktop in Firefox.
gameXML.xml
<?xml version="1.0" encoding="UTF-8" ?>
<users>
<user>Bob</user>
<user>James</user>
<user>Karen</user>
<user>Tom</user>
<user>Linda</user>
</users>
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>Test Page</title>
</head>
<body>
<p>
<label>List of users:</label>
<input type="button" value="XML" id="users" onclick="xmlOpen()">
<table id="tbody"></table>
</p>
<script language = "JavaScript">
xmlOpen = function(){
var users, i, len;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET", "gameXML.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
users = xmlDoc.getElementsByTagName("user");
len = users.length;
for (i = 0; i < len; i++) {
var user = users[i].firstChild.nodeValue;
var tr = document.createElement("tr");
var td = document.createElement("td");
var textNode = document.createTextNode(user);
td.appendChild(textNode);
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
}
}
</script>
</body>
</html>
Screenshot of result:

did you forget to display the data? If so, add this to your function:
document.getElementById('users').innerHTML = xmlDoc;
If that does not work, change responseXML to responseText.
If that does not work, try replacing
xmlhttp.open("GET","gameXML.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
with
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("users").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gameXML.xml",true);
xmlhttp.send();

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>

Read the xml in 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.

javascript code is not working in browser?

Here is my code it will send get request and renders some content of the response in html.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mytitle</title>
</head>
<body>
<script type="text/javascript">
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.send();
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
</script>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
<div id="placeholder"></div>
</body>
</html>
this code is working perfectly when i run in eclipse browser. but its failing in Browser.
I have checked browser configuration for script enabling and its enabled. and also no issue with browser configuration.
Im new to javascript http requests.
Please suggest
I read somewhere that the Eclipse browser doesn't adhere to the same origin policy [Wikipedia]. That's why it is possible to make an Ajax request to an external URL, something that is not possible by default in a "normal" browser.
And indeed if I try to run your code [jsFiddle], I get the following error:
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
There are multiple ways to work around the same-origin policy [SO]. In your case it seems that the service supports JSONP [SO].
With JSONP, your not making an Ajax call to the server, but instead you are using the URL with a dynamically created script element. Script elements are not restricted by the same-origin policy and therefore can load data (code) from other servers.
The server will return a JavaScript file which contains a single function call. The name of the function is specified by you via a query parameter. So, if the JSON response is usually:
{"message":"accurate","cod":"200", ...}
by adding the argument callback=foo to the URL, the server returns
foo({"message":"accurate","cod":"200", ...});
(follow this URL to see an example for your service)
This response can be evaluated as JavaScript. Note that you can not turn every JSON response into JSONP. JSONP must be supported by the server.
Here is a complete example:
// this function must be global since the script is executed in global scope
function processResponse(obj1) {
document.getElementById("placeholder").innerHTML =
obj1.message + " " + obj1.list[0].name;
}
function httpGet() {
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
// the following line is just to explictly show the `callback` parameter
url += '&callback=processResponse';
// ^^^^^^^^^^^^^^^ name of our function
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
DEMO
If you google for JSONP, you will find more information [Wikipedia] and tutorials.
I think ur xmlhttprequest instance is not getting created. It is some time browser dependent try this..
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ your code }
In addition to needing a cross browser xmlhttpquest (which for that alone I'd use jQuery), you also need to wait for the document ready before accessing the city by id... that is, move your script block after your city definition (and I think you may need a form, depending on browser).
Perhaps something like this
<body>
<form>
<input type="text" id="city" />
<input type="button" value="submit" onclick="httpGet()" />
</form>
<script type="text/javascript">
function httpGet() {
if (typeof (document.getElementById("city")) == 'undefined') {
alert("Maybe console.log our alarm... but the sky appears to be falling.");
}
var xmlHttp = null;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
}
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp.open("GET", url, false);
xmlHttp.send();
}
</script>
<div id="placeholder"></div>
</body>
function httpGet() {
var xmlHttp = null;
var x = document.getElementById("city").value;
var url = "http://api.openweathermap.org/data/2.5/find?q=chennai&units=metric&mode=json";
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, false);
xmlHttp.onreadystatechange = function(){
var obj1 = JSON.parse(xmlHttp.responseText.toString());
document.getElementById("placeholder").innerHTML = obj1.message
+ " " + obj1.list[0].name;
}
xmlHttp.send();
}

Read file from HTML

I am trying to read a text file from my computer to a website. I have it working in IE, but I can't seem to make it work in Chrome. I'm not skilled in html really at all, so any assistance would be great!
<html>
<body>
<div id = "content">
</div>
<script lang = "javascript">
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // Internet Explorer 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","./Test.txt",false);
xhttp.send("");
xmlDoc=xhttp.responseText;
document.getElementById('content').innerHTML = xmlDoc;
</script>
</body>
</html>
Do it with the Javascript File API example here

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