what is wrong with my javascript structure - javascript

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.

Related

xml data is not showing in html page

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

Getting remote html page fails give me the php code itself instead, how to fix?

Well the problem is simple I need the javascript to get content of remote webpage, because there is no way to do it directly I am doing it from local php file and ajax in the java script just like this
The php file:
"getpage.php?url=http://stackoverflow.com" '
The php code :
<?php
$htm = file_get_contents($_GET['url']);
echo $htm; ?>
This code get content of the html page I direct him too.
The AJAX code :
function makeAJAXObject() {
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
return false;
}
}
}
return ajaxRequest;
}
'
And I call him latter in my script like this :
window.ajax = makeAJAXObject();
window.ajax.open("GET","getpage.php"+ queryString, true);
The problem is than I do
alert(window.ajax.responseText);
instead giving me the content of the url I asked him too Its give me the actual php script that I wrote above.
This script works on localhost just fine, but I need it to work form local computer without reuploading to any server, there is away to do it ?
Edit :
The php file is on the pc, I am building a win 8 app , it's not like I have a url or something.
You need to check your remote server configuration to make sure that PHP file are processed by the server. Make sure mod_php is installed in apache and you have the proper AddType to process php files.
See this question: why are my php files showing as plain text?
Also, this is a HUGE security issue, you need to check what is requested and/or whitelist it.
What if I call
getpage.php?url=/etc/passwd
getpage.php?url=/your/secret/file
Because you don't do any checks, you would simply return the results to me ...

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>

Can someone help me understand AJAX (JSON) problem?

My goal is to create an personal application out of my ActionScript3 video player. I want to be able to hold keep the single .swf file in my browser and through AJAX, pass the .swf the url to my videos. I've chosen to use JSON as my data.
I'm new to JSON and I've hit a wall. It seems completely easy, but at first I wasn't even able to even get my locally hosted .json file into my webapp. It was working when I tried to do this with XML. After a bunch of trouble shooting, it is now in fact getting my XMLHttpRequest.
I'm trying to keep with backwards compatibility as much as possible, and thus I'm using the json2.js library to secure that notion.
My current issue is not being able to parse my XMLHTTPRequest. To be honest, I'm not even sure if what I'm doing is right as everywhere I look for examples, they're almost all pointing to a solution that writes the JSON into the actual webpage.
My external JSON file: test.json.
{ "video":"test.f4v", "thumb":"test.jpg", "title":"The test", "caption":"TEST TEST TEST TEST TEST", "minutes":01, "seconds":43 }
I'm positive the JSON file is valid.
Here is my html/javascript:
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
window.onload = initAll();
function initAll(){
var jsonData = {};
var xhr = false;
if(window.XMLHttpRequest){ //Chrome, Firefox, Opera, Safari, IE7+
xhr = new XMLHttpRequest();
} else if(window.ActiveXObject){ //IE5 + IE6
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Could not make XMLHttpRequest");
}
}
}
if(xhr){
xhr.open("GET", "js/ajax/test.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200){
try{
jsonData = JSON.parse(xhr.responseText);
alert(jsonData.title);
document.getElementById("vidtitle").innerHTML = xhr.responseText.title;
document.getElementById("vidcaption").innerHTML = jsonData.caption;
} catch(e){
alert("Unable to parse jsonData.");
}
}
};
xhr.send(null);
}
}
</script>
</head>
<body><div class="vidcontent">
<h2 id="vidtitle"></h2>
<p id="vidcaption"></p>
I'm doing this locally on my server, but I have uploaded the files to my web host and still get the same issues.
Firebug tells me it has the data and I can even read it through the console. Now, The code works in Firefox, but not Chrome or IE8 (IE8 Works occasionally when I put it into compatibility mode, but not always <.< ) I can't test on Safari or Opera right now.
Is there any way I can get this working in these browsers? I have attempted $.parseJSON in the JQuery library, but I was having issues with that as well. I am interested in JQuery as well if anyone can explain the solution with it.
Your JSON is invalid: http://www.jsonlint.com/
Leading 0's are not allowed in numbers apparently.

Categories