xml data is not showing in html page - javascript

I am just trying to fetch xml data and showing it in html page using jscript. According to this tutorial i have written a sample code which is
<script>
xmlDoc=loadXMLDoc("http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml");
x=xmlDoc.getElementsByTagName('city');
for(i=0;i<x.length;i++)
{
att=x.item(i).attributes.getNamedItem("name");
document.write(att.value + "<br>");
}
</script>
<script >
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
My output in html page should be 'London'. But its showing nothing. Or plz tell about my mistake.

I think you're running into the infamous "same-origin policy" problem
To summarize, in AJAX you can't load XML content from a remote server, application or website (meaning XML data cannot originate from any domain outside of your own domain.
There area number of ways around this problem such as the use of a server-side proxy, instead of XML use JSONp or the use of CORS to break the sandbox your client app is in when running that code (if both your user's browser and the server-stack you're requesting to supports it).

Ajax is asynchronous.
You need to read about http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
That will do the business when the reply is received

Related

Run python file from JavaScript [duplicate]

What I want is run python script just click on the button in the html page and show the python code result on my page.
Because it's just a small project, so I don't want to be overkill learning Django or other web frames even though I know it will work.
I made some searches, ajax seems the right solution for me, but I don't know how to execute python code by ajax. I know I can get some string back via ajax using following code:
function loadXMLDoc()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
}
Thanks in advance for anyone who can help.
To extend #Liongold's comment, The full workflow goes like this:
Overview of how this happens
The javascript code for a button click gets executed. This code is running on the client from a browser.
The AJAX request gets sent over the internet just like an HTTP request, which is interpreted by a web application running on the computer that will run the Python code.
The python code creates a response, and formats it for sending back to the client.
The javascript reads the response as plain text, and decides what it means and how to use it. JSON is a very popular format for exchanging data via AJAX
What you need to do
Either:
Learn a server-side python framework. Flask is lightweight and will probably do what you want. The largest obstacle I've found here is dealing with Cross-origin (CORS) problems. Get started at http://flask.pocoo.org/docs/0.10/quickstart/
OR
See if you can port the python script INTO the browser. Does the code need to be run on a specific computer ( the server ) or could it theoretically be converted into javascript and run within the webpage. If the language difference is your only problem, have a look at http://www.skulpt.org/
I ran into a similar problem, and after searching for several hours, this is how i solved it. Assuming that the html file and the python file are the same folder.
<script>
function runScript() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
alert('Successful .... ' + request.responseText);
} else {
alert('Something went wrong, status was ' + request.status);
}
}
};
request.open('POST', 'test.py', true);
request.send(null);
return false;
};
document.getElementById('script-button').onclick = runScript;
</script>
This goes to your html file
-----------------------------
<button type="button" id="script-button">
add this line at the top of your python file
---------------------------------------------
test.py
------------
#!C:\Python34\python.exe -u
print("Testing 123")
add this directive to httpd.conf (Apache)
-----------------------------------------
# "C:/xampp/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "C:/xampp/<path to your project on the web server>">
AllowOverride All
Options Indexes FollowSymLinks Includes ExecCGI
AddHandler cgi-script .py .pyc
Order allow,deny
Allow from all
Require all granted
</Directory>

what is wrong with my javascript structure

I am really new on javascript. I want to read xml from an url and want to parse it on html. I have html and javascript codes like that:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
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;
}
xmlDoc=loadXMLDoc("http://www.w3schools.com/dom/books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
document.write(y.nodeValue);
</script>
</body>
</html>
What is wrong ? thanks
This is the standard method to do this task:
Since people keep going along the path of trying to use cross domain for something other than JSONP... IT WILL NOT WORK!
The following code below is an example of what will work, as your server is allowed to get content from other network locations being its more controlled.. Your browser on the other hand can only receive JSONP or PLAIN TEXT... Most google results should explain this as well..
YOUR ONLY OPTION
Is to use a PROXY of some form to obtain what your trying to access, So you only have three choices here.
Use JSONP or Plain Text
Use a Proxy or some other method that is local to your server/website/script/page
Keep trying to use examples posted here after being told cross domain rules apply.
JAVASCRIPT:
function loadXMLDoc(sURL) {
$.post( "myproxy.php", { requrl: sURL }).done(function( data ) {
alert(data);
console.log(data);
document.write(data);
});
}
PHP: myproxy.php
<?php
header('Content-Type: application/xml; charset=utf-8');
$file = file_get_contents($_POST['requrl']);
echo $file;
?>
Please note that is you plan to use this with other types of content then you will need to change/remove the header line.
YOUR BROWSER ALLOWS YOU TO AJAX XML FROM OTHER WEBSITES
If this is the case, then you need to replace or update your web browser..
THE ABOVE SOLUTION IS NOT COMPLEX
This is virtually copy and paste code ready to go, The JS function will return the result/data/content in the three most know ways...
The PHP script is a copy and paste as well.. So if you have PHP installed.
All you would need to do is create a new text file in the same location as your html document and name it as "myproxy.php" and this example will work.
This is a proper XmlHttpRequest with a callback function to handle your XML:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function loadXMLDoc(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function callbackFunction(response){
if (window.DOMParser){ // Non IE
var parser = new DOMParser();
var xml_doc = parser.parseFromString(response,"text/xml");
}else{ // Internet Explorer
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.loadXML(response);
}
// Do something with your 'xml_doc' object variable here
console.log(xml_doc) // Debugging only.. to see the XML in the browser console for your own reference
var x = xml_doc.getElementsByTagName("title")[0]
var y = x.childNodes[0];
document.write(y.nodeValue);
}
// Call the function to begin code execution
loadXMLDoc('http://www.w3schools.com/dom/books.xml')
</script>
</body>
</html>
This is working code so you can just erase what you have and put this directly in place of it. Good luck!
If you're planning on hosting the file on your own server to access via XHR, the code I offered is intended for that. If w3schools.com had a 'Access-Control-Allow-Origin: *' header on the XML file your are requesting, it would also work. But they don't. So you need to have the XML file in a place where your browser's security will let you access it (same domain origin as your webpage). Otherwise your browser will continue to block the resource with a 'cross-origin-request-blocked' error in the console.

Is CORS stopping my AJAX calls from working?

I'm porting a web app to Android (AppInventor AI2 created) to run in a WebViewer component.
I've got most things working but my AJAX calls to the API scripts on my webserver return null.
My guess is that the server is returning null because the origin of the request is an AJAX call from a standalone web page on my local machine (during dev) or a mobile device rather than coming from a page hosted on the same domain.
A bit of Googling around has turned up a lot of mentions of CORS...
Is this what is causing my problems?
If I call the api URL (it's a PHP script on my server that returns XML) direct from my browser I get the correct data returned.
I also have the same code running as part of the web app and that works fine.
The problem only seems to be when I am calling the HTML and JavaScript files from a local directory on my machine. (All other JavaScript function are working correctly, it's just those with AJAX calls that are getting null responses from the webserver that are causing me problems.
I have tried uploading the JS file to my webserver and calling that from the html but that didn't work either (It was a long shot as I guess the AJAX call is still actually being made from the local html file essentially).
Here is a full setup that can be used to test...
HTML file with JavaScript included:
<html>
<head>
<title>Test BBP App AJAX Error</title>
<script>
function getDataViaAJAX(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function () {
if (request.readyState == 4) {
alert("ready state of ajax changed to 4");
alert("request/data responseText=" + request.responseText);
alert("request=" + request);
// request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doTheLocalTest() {
getDataViaAJAX("./sample.xml", function (data) {
var xml = data.responseXML;
alert("Response is: '"+xml+"'")
});
}
function doTheWebTest() {
getDataViaAJAX("http://www.bluebadgeparking.com/sample.xml", function (data) {
var xml = data.responseXML;
alert("Response is: '"+xml+"'")
});
}
</script>
</head>
<body>
<input type="button" value="Click To Get XML from a local file" onClick="doTheLocalTest();">
<br />
<input type="button" value="Click To Get XML from the web" onClick="doTheWebTest();">
</body>
</html>
And a sample XML content (sample.xml):
<markers>
<marker id="1" descr="Whitefriars Street: One way street. Space on left." lat="51.5140241200000" lng="-0.1074814800000"/>
<marker id="1898" descr="Southern General Hospital, Surgical / Orthopaedic 1 Bay" lat="55.8635700800000" lng="-4.3390578030000"/>
</markers>
Save those to a local directory and try it.
When reading the XML from a local file it works, when loading the file from my webserver it fails with an empty response being returned.
(As an aside, I'm assuming I would have the same issues if I was developing a FireFox add-on that pulled data in via AJAX from my web server - something else I've been considering recently...)

Read XML File using Javascript from a Local Folder

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;

What's the best pratice to pass data to javascript from server side?

I knew exposing web service is a obvious option, is there any other quick method?
That question is too general to answer in any sort of useful way. But that said: a lot of people are using JSON for data interchange these days. If you're willing to use jQuery or another library, it's extra-easy to use AJAX to grab JSON and act on it. Otherwise, I imagine it's not that difficult with plain JavaScript either.
Your question is very vague, so I will try to answer it before some trigger happy mod closes it (sweet sweet reputation points!)
One option is Ajax. This lets you ask the server for information using PHP scripts
Client (HTML/Javascript)[1]:
<html>
<head>
<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){
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
It looks intimidating, but all you're doing is saying GET me the stuff in ajax_info.txt on the server, and when you do get it (onreadystatechange) write it out for me (console.log).
You can use the above and tweak it so instead of reading a text file it reads a PHP file. That way you could ask it to execute a PHP script, which reads the contents of the server (server type, database elements...) and returns it to the user. Here is How I do it (I use Dojo instead of pure javascript)
On the Client:
dojo.xhrGet({
url: 'getUser.php',
handleAs: "text",
content: {
title: "Mr. "
},
load: function(data) {
console.log(data);
}
}
on the server ('getUser.php'):
<?php
echo $_GET['title'] . get_current_user();
?>
The server will concatenate 'Mr.' with the current user and return it to the client which will print out something like so
Mr. www-data
Finally another way is to embed directly into javascript/html so when you load the page, the server automatically updates the source code (warning, this requires quite a bit of tweaking)
index.html/index.php [2]:
<html>
<head></head>
<body class="page_bg">
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>

Categories