updating objects from xml file through javascript (IE issue) - javascript

I've run into an issue with a simple javascript code, which is pretty much just a copy of the code here: http://www.w3schools.com/xml/xml_to_html.asp
<html>
<head>
<script type="text/javascript">
function displayMain()
{
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","catalog.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("VAR");
i=0;
variable1=(x[i].getElementsByTagName("VARIABLE")[0].childNodes[0].nodeValue);
name1=(x[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue);
value1=(x[i].getElementsByTagName("VALUE")[0].childNodes[0].nodeValue);
txt="Variable: " + variable1 + "<br />Name: " + name1 + "<br />Value: "+ value1;
document.getElementById("mainDiv").innerHTML=txt;
}
</script>
</head>
<body onload="displayMain(); setInterval('displayMain()', 1000)">
<div id='mainDiv'></div>
</body>
</html>
All I want to do is change the xml file and thus have the new value updated on the page. So for instance I change the value in the xml file it will reflect in the html page. It works great on Firefox and Chrome, but not on IExplorer. IE just keeps my old value in there, even when I refresh the page. The only way I can get it to update is by deleting the temp. files and history. Does anyone know a way around this? It dosn't seem very practical for a user to have to all that.

GET requests are cached. Set no cache headers on the server.
or
Append a random query string parameter
xmlhttp.open("GET","catalog.xml?qs=" + new Date().getTime(),false);

Related

Can't get xmlhttp.responseText value

I am trying to get the xmlhttp.responseText value, but I have no response from the xmlhttp. I was wondering if there is something wrong with my code:
SCRIPT
var xmlhttp;
function show(){
loadXMLDoc("includes/edit.php",function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
});
}
function loadXMLDoc(url,cfunc){
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
HTML
< a href="#" style="text-align: right; font-size: 10px;" onclick="show()">SHOW</a>
EDIT.PHP
print "1";
I don't see anything wrong with your code per se, but there are a lot of interactions that are opaque from this code snippet.
I can offer some troubleshooting tips, however:
Add a console log in your callback function (the one that you are running alert() in). Just "console.log('function is running');" on the first line. Then see if you get that far. I would put one in the opening line of show() as well -- maybe your click event isn't doing what you think it is.
Have your PHP server-side file write something to a log so you can be sure that the request is being received where you think it is.
Open your browser developer console and watch the network panel. You should be able to see the entire XHR transaction there. Is it being sent at all? If so, is it returning the content you expect?
If all this doesn't help, setup a test in jsfiddle and post the link here. We'll be able to help in a lot more detail that way.
Good luck.

Using CGI methods to pass a parameter from JavaScript to Perl script over a web server

Wise ones: I am still having extreme troubles with a web application I am building. I am using an APACHE 2 web server. When in localhost, clicking on test.html will pop up a test button which should run the javascript within my .html file.
test.html is as follows:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
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() {
var str, fileNameVar;
fileNameVar = "hello";
if (xmlhttp.readyState==4 && xmlhttp.status==200){
str = xmlhttp.responseText;
alert(str);
}
}
xmlhttp.open('GET', 'try.pl?name=fileNameVar' + encodeURIComponent(fileNameVar),false);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Example</h2></div>
<button type="button" onclick="loadXMLDoc()">test</button>
</body>
</html>
This web app has worked before when calling a perl script and printing its return value, but this time I am trying to pass a parameter from the javascript to my perl script [try.pl]. As you see I am trying to pass the variable fileNameVar which will hold a string or an integer.
Here is my perl script, try.pl:
#!C:/indigoampp/perl-5.12.1/bin/perl.exe
use CGI;
use strict;
use warnings;
my $cgi = CGI->new;
my $name = $cgi->param('name');
print "Content-type: text/plain\n\n";
print "$name";
So when the button is pushed in my web app, it should simply create an alert to the user which contains the word "hello".
Though, when I press the button, nothing happens. I don't know what I am doing wrong, as it seems to work for others. Essentially, my web app works but I want to add the functionality of passing a variable from the javascript to the perl script.
NOTE: I do not want to pass "hello" directly in my GET statement. I want it to pass whatever is stored in fileNameVar. Though, in this example, fileNameVar is set to "hello". Thanks for ANY help!
1) Put test.html in the htdocs directory of apache2.
2) Put try.pl in the cgi-bin directory of apache2.
3) Make try.pl executable(which is probably done automatically for you on Windows). On unix, you would write:
.../apache2/cgi-bin$ chmod a+x try.pl
4) Start apache.
5) Request the test.html page by entering the following in your browser:
http://localhost:8080/test.html
(substitute in whatever port apache is listening on)
6) In this line:
xmlhttp.open('GET', 'try.pl?name=fileNameVar' + encodeURIComponent(fileNameVar),false);
...you have a few problems. You defined fileNameVar inside a function, and you are trying to access fileNameVar from outside the function. Variables defined inside a function can only be seen inside that function(exception for things called 'closures', which are functions defined inside other functions).
Secondly, in your example, encodeURIComponent() would return "hello", so your url would look like:
'try.pl?name=fileNameVar' + 'hello'
or equivalently:
'try.pl?name=fileNameVarhello'
...which is probably not what you want. You want to write:
var fileNameVar = "hello";
....'try.pl?name=' + encodeURIComponent(fileNameVar)
Next, you need to put 'cgi-bin' in the path:
var fileNameVar = "hello";
......'cgi-bin/try.pl?name=' + encodeURIComponent(fileNameVar)
7) In the line:
print "$name";
the quotes don't do anything.
====
.../apache2/htdocs/test.html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function loadXMLDoc()
{
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)
{
var str = xmlhttp.responseText;
alert(str);
}
}
var fileNameVar = "hello"; //LOOK AT ME*******
xmlhttp.open(
'GET',
'cgi-bin/try.pl?name=' + encodeURIComponent(fileNameVar),
false
);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Example</h2></div>
<button type="button" onclick="loadXMLDoc()">test</button>
</body>
</html>
...apache2/cgi-bin/try.pl:
#!/usr/bin/env perl
use CGI;
use strict;
use warnings;
my $cgi = CGI->new;
my $name = $cgi->param('name');
print "Content-type: text/plain\n\n";
print $name;
url to enter in your browser:
http://localhost:8080/test.html
(substitute in whatever port you configured apache to listen on--it's specified in .../apache2/conf/httpd.conf)
Then click on the button.
"When in localhost, clicking on test.html" says to me you might be accessing the page with a file: url, which will keep XMLHttpRequest from working.
You also want to use a standard javascript library instead of native XMLHttpRequest calls. Most of the world uses jquery these days.

Javascript is working on Safari, but fails on others

There is some problem that I can't find out why the code worked on Safari, but failed on other browsers.
There is the html part
and the main javascript part.
The main problem that I find is:
While executing the function downloadurl(url, function), cannot find the XML tags "Info", and the markers array length is 0 on many browsers. However, it's ok on Safari. The part of javascript code is like:
downloadUrl("http://travel-taoyuan.tycg.gov.tw/content/travel/xmlcontentlist1.aspx", function(doc) {
var xml = xmlParse(doc);
var markers = xml.documentElement.getElementsByTagName("Info");
......
To alert markers, it will return "0".
And actually it should be "174"(Safari's result).
Thanks for answering my question.
hmmm, seems to be a syntax error. Different browsers will use a different syntax, and so it won't execute (or at best, not properly if your lucky).
Try something along the lines of....
<script type="text/javascript">
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","http://travel-taoyuan.tycg.gov.tw/content/travel/xmlcontentlist1.aspx",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("theMainTagName"); //TODO: this is the main tag ^(see note)
for (i=0;i<x.length;i++)
{
//TODO: code to handle each xml element
//this is the code to get the value from a particular tag: x[i].getElementsByTagName("theTagName")[0].childNodes[0].nodeValue
}
</script>
NOTE: ^the 'main' tag is, for example, in the case of this xml document, the 'main' tag is 'CATALOG'
Hope this helps. Sorry if it's not very clear, been a while since I worked with xml/javascript. Comment if you want further explanation

Cant get node value in XML, how can I get it?

Im currently using a simple looped XML script from on w3cschools and it works great:
if (p1p2total == 5)
{
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","xml/SearchRequest-12437.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
document.write("<tr><td class='c3c1'>");
document.write(x[i].getElementsByTagName("key")[0].childNodes[0].nodeValue);
document.write("</td><td class='c3c2b'>");
document.write(x[i].getElementsByTagName("priority")[0].childNodes[0].nodeValue);
document.write("</td><td class='c3c3b'>");
document.write(x[i].getElementsByTagName("customfields")[0].getElementsByTagName("customfield")
[0].getAttributeNode("id").textContent);
document.write("</td></tr>");
}
}
However on my third node value query, customfields, im trying to obtain the textContent of a node with the following path in my xml:
item -> customfields -> customfield id=10080 -> customfieldvalue
How can I get the textContent value of customfieldvalue? The parent node has to have an attribute of id=10080 because different items have a varying amount of customfield tags that have different childnode ids.
Please help!!!
I only need this to work in FireFox...
---EDIT---
Ok so I figured out that the xpath I will need to use is:
./customfields/customfield[#id='customfield_10080']/customfieldvalues/customfieldvalue/text()
So how can I replace the line
document.write(x[i].getElementsByTagName("customfields")[0].getElementsByTagName("customfield")[0].getAttributeNode("id").textContent);
to pull the textcontents of the Xpath I provided while remaining in the javascript loop? I need this to pull this Xpath for each
As far as I'm concerned you only have to call
document.write(x[i].getElementsByTagName("customfields")[0].getElementsByTagName("customfield").text;
Give it a try. There are several ways of reading and parsing XML from javascript. I wouldn't recommend w3schools for learning. Go to the roots, try MDN for the next time ;)
I hope it helps

read txt file via client javascript

I'm new to javascript and trying to open a txt file into var and then inject it to html div...
I tried to use fopen but I didn't succeed.
<script type="text/javascript">
file = fopen(getScriptPath("info.txt"), 0);
file_length = flength(file);
var content = fread(file,file_length);
var div = document.getElementById("myDiv");
//alert(div);
div.innerHTML = "";
div.innerHTML = content;
</script>
Although it says xml request this works perfectly fine for txt files too (server and client side).
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","YOUR_FILE.txt",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseText;
JavaScript has none of the functions you are trying to use.
To read files on the server in JavaScript, you can use XMLHttpRequest.
There is no easy way to read files on the client machine.
abandoned question:
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","YOUR_FILE.txt",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseText;
by Freek8
For security reasons, Javascript is made so you can not do this. However, a person has made a workaround which may work and posted it here.
Ok, I realize, it only works for files that are publicly accessbile on the server, which I believe is not what you want to do. Still, if you do find a way, it will be a hack like this, but it could also be fixed to not work at any time.

Categories

Resources