Getting a file from a server using Javascript - javascript

So, I wrote some JavaScript to grab an xml file from my desktop and display it on an html page. However, I now have added my xml file to a webserver (mongoose). I want to call the file from that server, but whenever I call the file from the server it dosen't work, but when I call it from my desktop it loads fine.
I want to swap
xmlhttp.open("GET","Devices.xml",false);
with
xmlhttp.open("GET","http://localhost:8080/Devices.xml",false);
Here is the code
<html>
<head>
<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","Devices.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// the <Device> list
x = xmlDoc.getElementsByTagName('Device');
// make a function that extracts the attributes out of a Node
function getDeviceAttributes(dvc) {
var name = dvc.getAttribute("name");
var uuid = dvc.getAttribute("uuid");
var id = dvc.getAttribute("id");
return "<p>name: " + name + "<br> uuid: " + uuid + "<br> id: "+ id + "</p>";
}
// loop through the list
// assuming order doesn’t matter
var txt = '';
for (var i = x.length; i--;) {
txt += getDeviceAttributes(x[i]);
}
//show the result on page load
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
</script>
</head>
<body>
<div id='showDevices'></div>
</body>
</html>
Does anyone know how I can get this to work?
I have been told to use AJAX and Jquery, but I have no idea how to or even where to begin.

It looks like you are repeating a lot of work that jQuery can do for you. Check out the documentation for the Get request method
So something like this:
$.get('http://localhost:8080/Devices.xml', function(data) {
$('#showDevices').html(data);
});
I believe that is the jQuery for what you are trying to do. Hope that helps.
-Charlie
Just some generic advice, you could also use the .load() ajax function if you didn't want to parse the response and this:
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
can be done in jQuery like this $("#showDevices").html(txt);

Related

Import XML with JavaScript function

I have a panel, that when clicked opens up and displays data. I would like to have the data come from a XML file.
The JavaScript function that I was using to display html text worked, so I was trying to use that function, but modify it to bring over the XML from another file.
The JavaScript function from the JS file:
function nameFunction () {document.querySelector("#collapse1> .panel-body").innerHTML = "Name works"};
The XML from the XML file
<dashboard>
<name>name goes here</name>
</dashboard>
The html file that calls the JS function:
<a data-toggle="collapse" href="#collapse1" onClick="nameFunction()" >Name</a>
Can the .innerHTML method be used for this task? If so, can someone provide an example?
function nameFunction () {
var xmlText = "<dashboard>"+
"<name>name goes here</name>"+
"</dashboard>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlText,"text/xml");
document.querySelector("#collapse1 > .panel-body").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}
hope this can help you ! (this works)
function nameFunction (){
var xhttp;
if (window.XMLHttpRequest) { // Create an instance of XMLHttpRequest object.
//code for IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "data.xml", false);
xhttp.send();
var xmlDoc = xhttp.responseXML;
document.querySelector("#collapse1 > .panel-body").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}
this works in firefox,(not in chrome - chrome doesn't have XMLHttpRequest API I guess)
so now you can parse xml file
you can import files using script tag.
<script id="xml" type="notjs" src="XX.xml"></script>
var xml = document.getElementById("xml");
Is this what you want?

javascript json parse from URL

UPDATED:
I'm trying to parse a response from a URL but have no idea if I'm doing it correctly.
The URL returns the following JSON:
{"make":"truck","date":"23 July 2009","colour":"pink"};
If i replace var newtext = xhttp.responseText; with
var newtext = '{"make":"truck","date":"23 July 2009","colour":"pink"}';
it works but as soon as i go back to the xhttp.responseText it just shows a blank page.
The code I'm using is:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
xhttp.open("GET", "https://url.com", false);
xhttp.send();
var newtext = xhttp.responseText;
var obj = JSON.parse(newtext);
document.getElementById("demo").innerHTML =
obj.make + "<br>" +
obj.colour + "<br>" +
obj.date;
</script>
</body>
</html>
You haven't defined your variable xhttp, but you are trying to call functions on it. This is resulting in the Uncaught ReferenceError error and causing the rest of the code not to run. To create an XMLHttpRequest object as you appear to be trying to do, put this at the top of your script.
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// the object actually exists here now so the functions can be called on it
xhttp.open("GET", "https://url.com", false);
xhttp.send();
...
Then you can continue on with the rest of your code, assured that your xhttp object has been initialized.
I don't normally recommend using w3schools, but the above code was copied from http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp

Why wont javascript work after being loading through ajax?

I have a main page with this script on it to load status.html into my info-box_main div
window.onload = ajax_req('scripts/home/php/status.html', 'info-box_main');
The status.html file that is loaded looks like this.
<div id="status_update">
<form id="status_form" method="post" action="/scripts/home/php/statusUpdate.php/">
<textarea name="status_update" placeholder="Type Link update here. " id="status_field" ></textarea>
<input type='submit' value='post'/>
</form>
</div>
<div id='status-box'>
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job){
alert("Welcome " + name + ", the " + job);
}
</script>
</div>
ajax_req function
function ajax_req(file_location, document_element)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} //ajax update request
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(document_element).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", file_location ,true);
xmlhttp.send();
}
Everything works fine except for the javascript. I get an error that says the function is not defined when I try to click the button. Any help would be awesome! This is just test javascript... not the actual javascript I need
Setting the innerHTML property of an element to a string of HTML content including <script> tags does not run the script content in any browser I know of.
If you are indeed using jQuery, there's absolutely no reason to code up your own ajax facility, and the jQuery .load() method will handle script content for you.
$('#info-box_main').load('scripts/home/php/status.html');
This should work if you include it in a script in the header.
window.onload = function () {
$('#info-box_main').load('scripts/home/php/status.html');
};
Alternative solution:
$(document).ready(function () {
$('#info-box_main').load('scripts/home/php/status.html', function () {
$("#status-box").bind("click", myFunction);
// Seperate javascript from html, and only bind event once hmtl has loaded.
});
};
function myFunction (name,job) {
alert("Welcome " + name + ", the " + job);
}
If you stick to inlining your javascript, I'd consider putting the script tag before any other tag (like the button tag in your example) that references values in the script tag. That way you're sure your script tag has been evaluated before its values are being referenced.

javascript xml reader

I will keep this very short:
I'm trying to make a loop through an xml-document for a gallery. I got a script that should work, but doesn't. Can anyone please tell me where I did wrong?
I didn't want to make this longer because the problem is simple and have been pondering over this since yesterday and this is the closest I get.
I want to loop through the xml-file and print out "path" and "file" first and most. I'm building a gallery and thought that the best way to save all the data for the images was an xml-file, but now I can't get it to loop correctly. In the script I made the page print out both x and i, which resulted with x being 1 and i being 0, hence it hasn't worked through the for-loop at all as I see it.
Any help would be appreciated, because I'm stuck. Been trying so many solutions that my head is spinning and I can't get any further without a nudge in the right direction.
The html/javascript:
<script type="text/javascript">
function displayResult()
{
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","../gallery/gallery.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("session");
for (i=0;i<x.length;i++)
{
img = "<img src='";
path = (x[0].getElementsByTagName("path")[0].childNodes[0].nodeValue);
file = (x[i].getElementsByTagName("file")[i].childNodes[0].nodeValue);
end = "' /><br />";
name = (x[i].getElementsByTagName("name")[i].childNodes[0].nodeValue);
txt = "x:" + x.length + "| i " + i + "<br />" + img + path + file + end + name + "<br />";
document.getElementById("content").innerHTML = txt;
//document.write(txt);
}
}
</script>
</head>
<body onload="displayResult()">
<div id='content'></div>
</body>
</html>
xml-file:
<gallery>
<session>
<path>../gallery/beauty/</path>
<item>
<file>_DSC2331.jpg</file>
<name>Picture 1</name>
</item>
<item>
<file>_DSC2339.jpg</file>
<name>Picture 2</name>
</item>
<item>
<file>_DSC2350.jpg</file>
<name>Picture 3</name>
</item>
<date>2011-08-03</date>
</session>
</gallery>
If I can make some suggestions:
Use the var keyword within functions to make those variables local to that function. The code you have at the moment would set values in the global namespace, which is often considered bad practice (e.g. you could overwrite other people's variables, or other people could overwrite yours). Also declare your variables at the start of a function, as they will be hoisted there anyway.
Split your code up into more meaningful functions. This way they become easier to read and often then become more reusable.
Make sure you loop through items as well as sessions.
Consider using a Javascript framework like jQuery. They can often simplify the code you have to write, and you will usually end up writing less code yourself.
.
<html>
<head>
<script type="text/javascript">
function loadDoc(url) {
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.open("GET", url, false);
xmlhttp.send();
return xmlhttp.responseXML;
}
function getContent(sessions) {
var items = null,
i = 0,
j = 0,
img = "",
path = "",
file = "",
end = "",
name = "",
txt = "";
for (i = 0; i < sessions.length; i++) {
items = sessions[i].getElementsByTagName("item");
path = sessions[i].getElementsByTagName("path")[0].childNodes[0].nodeValue;
for (j = 0; j < items.length; j++) {
img = "<img src='";
file = items[j].getElementsByTagName("file")[0].childNodes[0].nodeValue;
end = "' /><br />";
name = items[j].getElementsByTagName("name")[0].childNodes[0].nodeValue;
txt += "session[" + i + "] item[" + j + "]<br />" + img + path + file + end + name + "<br />";
}
}
return txt;
}
function displayResult()
{
var xmlDoc = loadDoc("../gallery/gallery.xml");
var sessions = xmlDoc.getElementsByTagName("session");
var txt = getContent(sessions);
document.getElementById("content").innerHTML = txt;
}
</script>
</head>
<body onload="displayResult()">
<div id='content'></div>
</body>
</html>
It would seem to me that you want to show all items.
Yet you loop over 'session', of which there is only one.
So at best you will get only 1 picture this way..
You probably want to loop over xmlDoc.getElementsByTagName("item") and still use the session one to have access to the path.

How to parse HTML from JavaScript in Firefox?(2)

Im trying to parse a HTML result of **XmlHttpRequest** in Firefox. Im expecting to receive the HTML result from XmlHttpRequests *responseText* but when Im calling an alert(responseText) nothing is displayed.
Ive followed the example from http://stackoverflow.com/questions/888875/how-to-parse-html-from-javascript-in-firefox but that doesnt work either.
Here is thecode to make myself clear:
<html>
<head>
<script type="text/javascript">
var http1;
var result;
function onPageLoad()
{
http1=getXmlHttpObject();
http1.open("GET", "https://login.yahoo.com/config/login_verify2?&.src=ym", true);
http1.send(null);
http1.onReadyStateChange=stateChanged();
}
function stateChanged()
{
if(http1.readyState==4)
{
result = http1.responseText;
alert("result"+ result);
var tempDiv = document.createElement('div');
tempDiv.innerHTML = result.replace(/<script(.|\s)*?\/script>/g, '');
// tempDiv now has a DOM structure:
alert(tempDiv.getElementById('username').size);
}
else
alert("mircea geoana la zoo");
}
function getXmlHttpObject()
{
var objXMLHttp=null;
if (typeof XMLHttpRequest!= 'undefined')
{
objXMLHttp=new XMLHttpRequest();
}
else
{
objXMLHttp=new ActiveXObject(Microsoft.XmlHttp);
}
return objXMLHttp;
}
</script>
</head>
<body onload="onPageLoad()">
<p>aaa<p>
</body>
</html>
http1.onReadyStateChange=stateChanged();
should be
http1.onReadyStateChange=stateChanged;
I see a big mistake there.. the message on the else branch should read 'miRcea', not 'micea'.. Tell me if this solves your issue, Mr claudiu ;))
this is how you should define the xmlhttp Object:
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
Check out this w3School tutorial to read about how to properly use AJAX calls and the like.
edit - my bad, only saw the line defining the call for IE6/5. Either way this method is much more clean.
You can only send AJAX requests to the same domain from which the JavaScript originates. And I'm guessing you're not sending your requests from "login.yahoo.com"...

Categories

Resources