I would like to retrieve fullpath of a file and pass it to javascript. The requirement is that I need to retrieve XML file using JavaScript.
If it is a file you can access relatively to your web page do something like:
var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false";
xmlDoc.load("abc.xml");
Assuming you have your web page next to the abc.xml...
This doesn't specify how to get full path to the XML - do youi still need it or loading it is enough?
For cross browser (from: http://developer.apple.com/internet/webcontent/xmlhttpreq.html)
var req;
loadXMLDoc("abc.xml");
function loadXMLDoc(url) {
req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send("");
}
}
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
alert(req.responseXML);
} else {
alert("There was a problem retrieving the XML data:\n" + req.statusText);
}
}
}
If you know the exact file up front, you can create a server-side program (i.e. service) to read the file, parse it and output it.
Then you'll just need to write some Javascript to make an AJAX call to this service (check out a Javascript library like Prototype or JQuery) to read the output of the service and thus the contents of the file.
Related
In my website I am currently trying to write code to turn a link into a formatted attachment .
I am trying to write code to detect if the file exists
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
alert(doesFileExist("http://hexbugman213.net/favicon.png"));
However, I noticed a problem. When the website has a 404 handler like .htaccess, and I try to test it with the file, it sees that the website didn't return a 404, and therefore still says it exists.
function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
if (xhr.status == "404") {
return false;
} else {
return true;
}
}
alert(doesFileExist("http://hexbugman213.net/thisfiledoesntexist.mp3"));
Is there any way I can account for this and have it return "false" when the file doesn't exist even if there's a 404 handler?
You need to call the send() function on the XMLHttpRequest to make it actually make the request. See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
Also, you may run into cross origin issues depending on exactly what URL you're trying to retrieve and where you're hosting the page from. Mozilla has some documentation on the subject if you're not familiar with it: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Here is an improved version of your JavaScript that checks for exceptions and calls the send() function.
function doesFileExist(urlToFile) {
try {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
alert(xhr.status)
if (xhr.status !== 200) {
return false;
} else {
return true;
}
} catch (e) {
alert(e);
return false;
}
}
alert(doesFileExist("https://server.test-cors.org/server?enable=true&status=200&credentials=false"));
alert(doesFileExist("https://server.test-cors.org/server?enable=true&status=404&credentials=false"));
alert(doesFileExist("https://www.google.com/"));
alert(doesFileExist("http://hexbugman213.net/thisfiledoesntexist.mp3"));
The host: https://www.test-cors.org/ in the example is useful for testing CORS.
I am trying to write a javascript function that tries reading text files from the server until it finds one that doesn't exist.
On the server there are text files numbered 1 to n (1.txt, 2.txt, 3.txt etc.), so it should read all the files (sequentially or asynchronously) until it tries to read "4.txt" and it throws an error.
The following code works on my local machine (with no server running), but fails on a remote server saying the "No such file" error is uncaught.
I am trying to understand why the error is handled differently in the two cases, if there is anything I can do to make it work for a remote server as well, and if there is any other approach I can take for this?
The minimal code I have is:
var files=[];
function readTextFile(file)
{
var request = new XMLHttpRequest();
request.open("GET", file, false);
request.onreadystatechange = function ()
{
if(request.readyState === 4)
{
if(request.status === 200)
{
var allText = request.responseText;
files.push(allText);
} else {
throw "No such file";
}
}
}
request.send();
}
function readFiles(){
try {
var i =1;
while (true) {
readTextFile(i+".txt");
i+=1;
}
}
catch (e) {
console.log("finished reading files")
}
console.log(files)
}
readFiles();
I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.
UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:
var materialFilename;
function loadOBJModel(filename)
{
// ...
var req = new XMLHttpRequest();
req.open('GET', filename);
req.responseType = 'text';
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line)
{
readLine(line);
});
}
}
req.send();
alert(materialFilename);
// ...
}
function readLine(line)
{
// ...
else if (tokens[0] == "mtllib")
{
materialFilename = tokens[1];
}
// ...
}
You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.
To scan line-by-line, you can use split(). E.g. Something like this ...
var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line, i) {
// 'line' is a line of your file, 'i' is the line number (starting at 0)
});
} else {
// (something went wrong with the request)
}
}
}
req.send();
If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.
You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.
Once you have the data, parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for that out of the box.
I have web application that can download from dropbox.com. The application is written using Javascript. I'm using the dropbox.min.js http://code.google.com/p/dropbox-js/ library running on a client.
This is a function of the library:
client.readFile(name, function(error, data) {
if (error) {
return showError(error); // Something went wrong.
}
saveFile(name, data);
});
saveFile(name, data) is my function doing the following:
var saveFile = function(file, data)
{
var xmlhttp = getXmlHttp();
xmlhttp.open('POST', 'saving.php', true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("fileName=" + file + "&data=" + data);
}
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
The problem is: while I'm trying to download assets (e.g. jpg doc, gif, etc.), I only receive 1kb instead of the full file. Are there any workarounds?
The official JavaScript library can download binary files in browsers that support XHR level 2 (Chrome, Firefox, IE 10).
See the sample code in the getting started document, and use the blob: true option when calling readFile.
i have a url which returns a json file(i have typed the url in the address bar and it showed the json output) but i don't know how to request for the json file in javascript. can anybody help me?
here's the code:
var url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=kalutara&format=json&num_of_days=4&key=myKey' ;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
http_request.open('GET', url, true);
http_request.send(null);
http_request.onreadystatechange = function() {
if ( http_request.readyState == 4) {
if ( http_request.status == 200)
success( http_request.responseText);alert(http_request.responseText);
else if (failure)
failure( http_request.status, http_request.statusText);
}
};
Thanks !!
It depends on how you json file looks like.
For e.g.
If the file contains something like
var obj =
{
//Object definition...
}
Then you can just use the regular script tag to be able to use the json object.
If the file in format:
{
//Object Definiton
}
then you can read the contents as defined in your post (Using XMLHTTP request) however then use eval function to make it available in the page something like the one below in your success() method:
eval("var obj = " + http_request.responseText);