xmlhttprequest javascript - where do i place my json file - javascript

Ive got this code in my script tag at my index file
var xhr = new XMLHttpRequest();
xhr.open("GET","images.json",true);
xhr.onload = function () {
parsedJSON = JSON.parse(this.responseTEXT);
console.log(parsedJSON["frames"]["turn.png"]["rotated"]);
};
Ive executed it through my localhost on node.js
however it keeps coming up with 404 not found.
now i dont now where to put the file at.
in developer tools it shows that its been seached for at http://localhost:2000/images.json
i do not now where or how to place it in the local host, can anyone help
sorry for broken english.

If you're using Express...
Try creating a folder called public in the same folder as the file you execute with Node. Then, just pass that folder name to the express.static middleware like this:
app.use(express.static('public'));
If you put images.json into the public folder now, express.static will find it and send it to your browser when the file is requested by your script.
And, as epascarello pointed out, JavaScript is case-sensitive. You'll want to change responseTEXT to responseText.

Related

how to read text file in folder with javascript

I have a folder structure like this
index.html
file.txt
in the index.html I have a script that wants to read the file.txt and assign it to a variable, say x.
async function loadFile(file) {
let text = await file.text();
console.log(text);
return text
}
var x = loadFile("file.txt")
but this returns an error
main.js:35
Uncaught (in promise) TypeError: file.text is not a function
at loadFile (main.js:35:27)
at main.js:39:13
what to do? I just want to assign file.txt content to a variable.
JavaScript in browser doesn't give you direct access to file system.
What you did is just pass a string to your function and call text() on it. Sadly it doesn't work like that.
Here are two workarounds I know of:
1. fetch api
If you have an http server serving your files then you make a request using fetch() to obtain its content in JS. Read the docs here :
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Note that it won't work on pages loaded with file:// URI scheme. You need http(s). If you have python installed run python -m http.server 8000 in directory containing files to be served.
2. FileReader
If the file is to be selected by user as input to a form then you can use FileReader
Have a look these links:
webdev has great explaination for this
https://web.dev/read-files/
also see the docs
https://developer.mozilla.org/en-US/docs/Web/API/FileReader

PHP to Javascript: dirname and document_root

I got a little problem. I am working on a project and I got my root, then I got 2 folders: website1 and website2.
website1 is the staff panel, where the upload script is on (where this problem is on). website2 is the website the 'customer' will see. Here all the uploaded images, PDFs etc. are uploaded to.
So, I have a few notes before I start:
I cannot use PHP in my Javascript. The Javascript is in .js files and not in my .php file.
I cannot do this at my AJAX request as something client-side has to be done correctly to see the image.
So basically, I am in website1 and when I upload a file (with DropzoneJS (http://www.dropzonejs.com/)) it does a AJAX request. Here it has to upload a file to a directory in website2. In website1 I have to see that image after uploading it in a IMG tag.
So in PHP I got this:
$uploadPath = filter_input(INPUT_POST, 'uploadPath');
$uploadPath = dirname(getenv('DOCUMENT_ROOT')) . '/' . $uploadPath;
This works and the file gets uploaded to that directory. $uploadPath is this (in Javascript, sent as POST parameter in AJAX request):
/SITE2/assets/uploads/
Now I need to translate the dirname and getenv('DOCUMENT_ROOT') into Javascript. I tried document.location.hostname but this does return a different value than getenv('DOCUMENT_ROOT').
document.location.hostname: 127.0.0.1
getenv('DOCUMENT_ROOT'): D:/xampp/htdocs
How can I get the same value as getenv('DOCUMENT_ROOT') in Javascript?
In php file you can create script with JavaScript variable like this:
<script>
var DOCUMENT_ROOT = "<?= getenv('DOCUMENT_ROOT') ?>";
</script>
the other option is to have your JavaScript file as PHP script then you can use PHP code inside.
You have two options, but I caution you sending the actual file path on the server/disk to the client side is a bad idea.
Use Ajax so the client sends a request like $.ajax({url: "getdir.php", success: someJSFuntion } );
Change your JavaScript file to be a ".php" file and then include the code right in there.
There is no spec that says you can't have your JS file be a ".php" file. So you'd link to it like this:
<script type="text/javascript" src="/js/myjs.php"></script>
And that would let you use PHP directly in your JS file.
Check out php.js for a JavaScript port of dirname...
http://phpjs.org/functions/dirname/
As for getenv('DOCUMENT_ROOT'), you can't get this variable value via JavaScript. The reason for this is the client-side "location" of the JavaScript file says nothing about it's actual location on the server. The best you can do is get the parent directory of the file or the domain name.
For example:
http://example.com/path/to/file
The "DOCUMENT_ROOT" as far as JavaScript is concerned is...
/path/to
It seems very improper to even assume the need to have the server-side location of the file available to the JavaScript. I would simply use either a specific URL query that indicates what location to use, or to send the location back with the AJAX response since you can add whatever you need there.
{
"document-root": "/SITE2/assets/uploads/",
"normal-response": {
...
}
}
And then wherever you would normally use what is normally received, this use...
// For example
var response = JSON.parse (request.responseText);
// Normal response
console.log (response['normal-response'][...]);
// Document Root
console.log (response['document-root']);

How to read local xml file using javascript?

Maybe the problem is that i wrote path to my file incorrectly, i'm using Linux, do i have to write path in some different way?
<script type="text/javascript">
function func(){
var xmlFile = new XMLHttpRequest();
xmlFile.open("GET", "/home/kat/course/data.xml", false);
xmlFile.send();
xmlDoc = xmlFile.responseXML;
document.getElementById("result_field").value = xmlDoc;
}
</script>
The file needs to be in the webroot.
So if you have the code in /var/www and your site is 'somedomain.com/index.html' you will need to have the xml file in the same /var/www directory and access it like "GET", "somedomain.com/anotherfolder/data.xml"...
You can't access server directories from JS... The javascript runs on the client side, not on the server side, so the file needs to be accessible on the website.
JavaScript can only access files your server is serving. Unless you are serving /home/kat/course/data.xml, you're going to need to move data.xml before your JavaScript can access it. Once you move it to a location being served, it will be accessible via an XHR.
As a side note, the responseXML property of an XHR is a Document object, not a string. See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML
There could be two problems. The url must be {your_server_domain}/home/kat/course/data.xml, and the document.getElementById("result_field") must be an input/textarea to accept value attribution, otherwise, use innerHTML.
P.s.: Your local server domain usually is: localhost or 127.0.0.1:80.

Again: how can I read a file using javascript

I could not find out why this part of my code doesn't work:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
var FilePath = dir + "/" + FileName;
var file = new File("FilePath");
var reader = new FileReader();
reader.onload = function(e) {FileText = reader.result;}
reader.readAsText(file);
alert (FileText);
The intention is, I think, clear: FilePath contains the filename of a file (passed via parameter FileName) containing logging data (a plain ASCII text file, with one line per log entry), the file is located in the same directory as the web page is (loc), and I want to embed the text into my html document somewhere further down the code.
Since the logged lines are of different kinds (e.g. errors, warning, other blabla ...) each line needs to be parsed and processed.
I intended to split FileText into an array, and loop through it. I cannot, however, get readastext to work. Though, according to FireFox debugger, FilePath does contain the correct string, I get the NS_ERROR_FAILURE, which I, according to the sparse documentation I found about it, must consider to be the 'zillionst stupid way to say "File not found".
I found tons of other posts from people messing with the file API, and tons of snippets taken from the mozilla docs which don't help me out. I read that there are maybe other ways to read a file, e.g. through Ajax, JQuery ... but before I go that way ... is it really, really absolutely impossible to accomplish what I want using just plain JavaScript, and if it is possible, who can provide a code snippet?
Thanks very much,
Armin.
You have quotes around "FilePath":
var file = new File("FilePath");
This means it's going to try to load a file with the path "FilePath".
Pretty sure this is what you want:
var file = new File(FilePath);
On the other hand, Quentin is absolutely right. You're not going to be able to access local files if this code is running in a web page.
Since you are using window.location.pathname i assume that you are in a browser and want to use that code to "navigate" to files on the server based on the URL path.
I think your whole approach is wrong, and it would be a security issue to have something like that possible.
The File API can be used strictly on files selected by the user, and not on any file. The MDN description is self-explanatory:
Using the File API, which was added to the DOM in HTML5, it's now possible for web content to ask the user to select local files, then read the contents of those files. This selection can be done by either using an HTML element, or by drag and drop.
Yes, you can specify a path to any file in the File constructor method, but that doesn't mean you can access any file. Another excerpt from MDN:
This only works from privileged code, so web content can't do it. This protects users from the inherent security risks associated with allowing web content free access to the contents of their disks. If you pass a path to the File constructor from unprivileged code (such as web content), an exception will be thrown.
This code did the trick:
var objXMLhttp = new XMLHttpRequest()
objXMLhttp.open("GET",strFileName,true);
objXMLhttp.send();
and, in addition, an objXMLhttp.onreadystatechange=function() ... event handler must be implemented, which is the code acutally receiving the data, like so:
objXMLhttp.onreadystatechange=function()
{
if (objXMLhttp.readyState==4 && objXMLhttp.status==200)
{
var arrContents = objXMLhttp.responseText.split("\n"); // gotcha!
....
}
}
Easy win is to do an ajax request for the path...you should have your page that contains the js and files served by a web server. Any other way needs other priveleges and if you were to get files from a users computer without an uploader or anything like that would be a security breach

is there a do/workaround XML requests without HTTP

I want to get the string from a file in javascript but it doesnt' work. The error says that it is because Cross origin requests are only supported for HTTP. So the only reason this doesn't work is evidently because the HTML page isnt online. Is there a way to read a .txt file into a string that can workaround this issue
this is the code that doesn't work:
function readTextFile(file)
{
var File = new XMLHttpRequest();
File.open("GET", file, true);
File.send(null);
Text = File.responseText;
return Text;
}
At line 6 is stops and display the error.
Thanks in advance:)
You cannot use it for a local file for security reasons I believe, it should work as long as you make the file variable a valid http url to the file. You can use xampp / wampp / mamp / etc to create a local webserver and run it from there !
that way your link can be like http://localhost/link/to/file.txt

Categories

Resources