I am trying to read the XML of an RSS feed on a website (that I do not have control over) and display it using Javascript. I used the following code to extract the data and it works, but the major caveat is that this will only work in IE 8 (Ugh).
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",<URL with xml extension>,false);
xmlhttp.send();
setTimeout("wait()",3000);
function wait()
{
alert("complete");
}
var xmlDoc = xmlhttp.responseXML;
var data = xmlDoc.getElementsByTagName("entry");
The wait function currently exists to give the server time to respond to my xmlHTTP request. Does anyone know a workaround in Javascript, AJAX or something similar that would give me functionality on current versions of Firefox, Chrome, etc?
I think you should use JFeed, its faster and its really easy to use, your code is a bit long, with Jfeed you can do it like that:
jQuery.getFeed({
url: '<URL with xml extension>',
success: function(feed) {
alert(feed.entry); //your element
}
});
let me know if you need help with that.
Good luck.
Related
Just getting to grips with ajax and noticed that when I wanted to include javascript in the document I link to / open
xmlhttp.open("GET","ajax_info.txt",true);
then the script doesn't work. However if I use jquery ajax then the javascript I add works fine.
Am I missing something?
This is because you can't do this with just one line. jQuery has spoiled us into making it look very easy and small, but it's actually a tad more complicated.
You never start the XMLHttpRequest, which is the actual magic:
// figure out what kind of support we have for the XMLHttpRequest object
if (window.XMLHttpRequest){
//modern browsers
req = new XMLHttpRequest();
}
else {
//good ol' lousy IE
req = new ActiveXObject("Microsoft.XMLHTTP");
}
This page explains the steps which have to be taken for a full XMLHttpRequest().
I am trying to learn how to read into a web page data in an XML file. This is a static HTML page. I do not want a web server and I cannot use Ajax. The XML file is local (in the same directory as the HTML file). I want this to work in a Chrome browser.
What I need to do is:
Read the XML file on the page onLoad event.
Use innerHTML to insert the XML data into a div.
My problem is in reading the XML file. All of the examples I have found I think will only work if there is a web server running, which I have to avoid.
If you're reading another file the only way to do that with front end JS is another request (ajax). If this were node.js it would be different because node can access the filesystem. Alternatively if you get the xml into a javascript string on the same page, you can manipulate it. There are a number of good libraries (jquery's parseXML).
Original answer here: https://stackoverflow.com/a/48633464/8612509
So, I might be a little late to the party, but this is to help anybody else who's been ripping his/her hair out looking for a solution to this.
First of all, CORS needs to be allowed in the browser if you're not running your HTML file off a server. Second, I found that the code snippets most people refer to in these kind of threads don't work for loading local XML-files. Try this (example taken from the official docs):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', true);
xhr.timeout = 2000; // time in milliseconds
xhr.onload = function () {
// Request finished. Do processing here.
var xmlDoc = this.responseXML; // <- Here's your XML file
};
xhr.ontimeout = function (e) {
// XMLHttpRequest timed out. Do something here.
};
xhr.send(null);
The method (1st arg) is ignored in xhr.open if you're referring to a local file, and async (3rd arg) is true by default, so you really just need to point to your file and then parse the result! =)
Good luck!
Since you're only targeting Chrome, you could take a look at the File API. You'd have to prompt the user to select the file or drop it into a specific area of the page though, which might be something you'd rather avoid, or not. The following HTML5 Rocks article should help.
Assuming the HTML, XML and browser are all on the same machine, you might try using an Iframe in the HTML that references the XML using a URL like file:\.
You could do something like this:
<html>
<head>
<script type="text/javascript">
//If using jQuery, select the tag using something like this to manipulate
//the look of the xml tags and stuff.
$('#xframe').attr('style', 'thisxmltag.....');
</script>
</head>
<body>
...
<frame id="xframe" src="the_xml_doc"></src>
</body>
</html>
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", file_Location, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById(your_div_id).value =
xmlDoc.getElementsByTagName(The_tag_in_xml_you_want_to_display)
[0].childNodes[0].nodeValue;
Works with IE11
<head>
// To be hidden with a better method than using width and height
<OBJECT id="data1" data="data.xml" width="1px" height="1px"></OBJECT>
// to work offline
<script src="lib/jquery-2.2.3.min.js"></script>
</head>
<body>
<script>
var TheDocument = document.getElementById("data1").contentDocument;
var Customers = TheDocument.getElementsByTagName("myListofCustomers");
var val1 = Customers[0].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:
<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
and (with file_inhoud, lines defined elsewhere)
function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
Debug function shows:
readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
So statement that stops the program is:
var file_inhoud=doc.document.body;
What is wrong? What is correct (or best) way to read this file?
Note: I see that the file is read and displayed in the frame.
Thanks!
Your best bet, since the file is on your server is to retrieve it via "ajax". This stands for Asynchronous JavaScript And XML, but the XML part is completely optional, it can be used with all sorts of content types (including plain text). (For that matter, the asynchronous part is optional as well, but it's best to stick with that.)
Here's a basic example of requesting text file data using ajax:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
You'd call that like this:
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
However, the above is somewhat simplified. It would work with modern browsers, but not some older ones, where you have to work around some issues.
Update: You said in a comment below that you're using jQuery. If so, you can use its ajax function and get the benefit of jQuery's workarounds for some browser inconsistencies:
$.ajax({
type: "GET",
url: "path/to/file",
success: function(text) {
// `text` is the file text
},
error: function() {
// An error occurred
}
});
Side note:
I found that javascript is client based...
No. This is a myth. JavaScript is just a programming language. It can be used in browsers, on servers, on your workstation, etc. In fact, JavaScript was originally developed for server-side use.
These days, the most common use (and your use-case) is indeed in web browsers, client-side, but JavaScript is not limited to the client in the general case. And it's having a major resurgence on the server and elsewhere, in fact.
The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.
I'm having problems reading an XML local input. The weird thing is that this code works perfectly when the XML is located on a server(This is desktop, by the way, so no SOP problems). I can't figure this out for the life of me, and I've been staring at it, trying different things for a couple of hours.
And another question: does the XML document need a css sheet to be properly read? I would imagine that it doesn't, but I don't know too much about it.
function verify()
{
zipObj = new ActiveXObject("Msxml2.XMLHTTP");
zipObj.open("GET", "KMSY.xml", false);
zipObj.onreadystatechange = function() {
if (zipObj.readyState === 4) {
zipXML = zipObj.responseXML;
read(zipXML);
}
else {
document.getElementById("notice").innerHTML = zipObj.readyState;
}
}
zipObj.send();
}
function read(zipXML)
{
var temp = zipXML.getElementsByTagName("temp_f")[0].childNodes[0].nodeValue;
document.getElementById("notice").innerHTML = temp;
}
Import the XML file to a local server, AJAX obviously needs the XML files to be on web server in order to parse them, or so my humble experience tells me.
You might also want to add the compatibility code for other XML requests into your code.
new XMLHttpRequest() for all browser and IE 8+
new ActiveXObject("Microsoft.XMLHTTP") IE prior to 8
I know what GET and POST methods are in ajax, but i was wondering how to implement them into a simple code so i can understand it better, and here's a simple code i found:
<html>
<head>
<title>XMLHttpRequest in Mozilla</title>
<script type="text/javascript">
function Start()
{
try
{
xmlhttp = new XMLHttpRequest();
document.getElementById("Content").innerHTML="<h1>Using XMLHttpRequest Object</h1>";
}
catch (e)
{
document.getElementById("Content").innerHTML="<h1>XMLHttp cannot be created!</h1>";
}
}
</script>
</head>
<body>
Start
<div id="Content"></div>
</body>
</html>
The only thing you're achieving there is to determine whether your browser supports XMLHttpRequest or not (no in explorer, yes on anything else). You are not actually calling the server.
This is a nice link to start learning ajax and javascript in general:
http://www.hunlock.com/blogs/AJAX_for_n00bs
Be sure you check all the site, not only that post.
function ajaxRequest() {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest) { // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null) { // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
var url='http://somedomain.com/getdata.php?doc=sometext.txt'; // This is the URL we will call.
AJAX.open("GET", url, true); // Open the url this object was set-up with.
AJAX.send(null); // Send the request.
AJAX.onreadystatechange = function() { // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete") { // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
}
// End Ajax readystate check.
} // End Event Handler.
}
A good place to get started : https://developer.mozilla.org/en/AJAX/
Your snippet of code will only work in non IE browsers. Don't leave MS out of the party! Use this code
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
Now you can use this object to carry out a request or two.
There's a very comprehensive tutorial here : https://developer.mozilla.org/en/AJAX/Getting_Started
That tutorial will explain it much better than I ever can.
I would like to suggest something that will make your life a whole lot easier. Use jQuery! It makes ajax calls (and anything javascript) much easier. You can do complex operations with very little code.
http://api.jquery.com/jQuery.ajax/
This is for your refrence.
If you are really into Javascript and want to learn AJAX in simple way, I would suggest you the http://w3schools.com/ajax/ajax_intro.asp which is pretty basic and easy to understand. You can even try out there what you have learnt so far.
Also, Jquery is pretty simple as far as Ajax is considered. It basically frees you from all the mess of checking for the browser compatibilities and other stuff. I suggest you take a look at what Elad has mentioned in the above. "Write Less Do more" is the tag for Jquery. Just give it a try.