Write to file in JS using XMLHttpRequest? - javascript

I figured out how to read a local .TXT file on the server into JS using the XMLHttpRequest API but for the life of me I cant get it to write to the file. Is it possible or is this only for reading the files in?
My code to read in works fine:
var fReader = new XMLHttpRequest();
fReader.onreadystatechange=function() {
if(fReader.readyState==4 && fReader.status==200) {
parseText(fReader.responseText);//Processes the file.
}}
fReader.open("GET",fFileLoc,true);
fReader.send();
I'm currently using PHP to write to the file, but it's far from ideal. I'd really like to us JS to do it. Any thoughts? Is there another approach to doing this? Is PHP the only way?
Thanks in advance,
-Dave
EDIT: #rjmunro +others: I found that using PHP was the better way to go about this... My revised code is as follows. (C&C welcome).
JS:
var fReader = XMLHttpRequest();
//var params = "MODE=GET&File=Data.txt";//To read
//var params = "MODE=POST&File=Data.txt&Message=" + myMessage;//To write
fReader.onreadystatechange=function() {
if(fReader.readyState==4 && fReader.status==200) {
//Not really any response text if writing...
parseText(JSON.parse(fReader.responseText).GET);
}
}
fReader.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
fReader.setRequestHeader("Content-length", params.length);
fReader.setRequestHeader("Connection", "close");
fReader.send(params);
PHP
$MODE = $_POST['MODE'];
switch($MODE) {
case('GET'):
#Read in file and process, then return output.
$return['GET'] = file($_POST['File']);
break;
case('POST'):
if(file_exists($_POST['File'])){
$file = fopen($_POST['File'],"a");
$data = $_POST["Message"];
fwrite($file,$data);
fclose($file);
}
#$return['POST'] = "some message?";
break;
}
echo json_encode($return);
The only thing i'm not 100% on with this solution is why i have to setRequestHeader?
Chrome actually doesnt seem to like this... I pulled the code from another post.

XMLHttpRequest allows you to make HTTP requests.
If you want to use it to write to a file, then the HTTP server must respond to the request by writing a file.
You could use the PUT verb to do this (note that you will have to configure the HTTP server to allow this, no HTTP server will allow arbitrary users to write files to the server's disk by default).
You could also pass the data using POST or another request type.
Is PHP the only way?
You can use any programming language you like on the server (subject to what the server supports, e.g. if you want to use C# then you almost certainly want a Windows server with IIS and ASP.NET). If you want to use JavaScript then there are many options, of which Node.js is significantly more popular then the others at present.

You can probably configure apache to accept PUT requests, then send one using XMLHttpRequest (I'd use jQuery.ajax() to abstract this).
It's probably better to have PHP (or another server side language) handle it for you, though, as it will be difficult to control the authentication using only Apache.

Related

JavaScript Basic Solution for Retrieving Files

I'm very new to JavaScript, so please be patient with me. I've got a CSV file published to the web via Google, which is updated periodically. I have the URL of the file, and I want to write JS code which will retrieve that file when an HTML page is loaded, then convert it into a string so I can manipulate it and scoop out the values I want to place in different elements. The problem is, I have no idea how to request items from different URLs. I'm guessing there's some built-in functionality in JS to do what I want, but I'm completely in the dark on how to find it. Care to help me out?
What you're looking for is the XMLHttpRequest, but I'd recommend using jQuery's $.ajax() function as it decreases the complexity of sending asynchronous requests.
You can use jquery $.ajax or better Fetch API or axios to get the file contents.
Then you need to process it by using something like Papa Parse.
PS. Papa Parse actually supports remote files directly so you can try that.
Sounds like what you're looking for is AJAX.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
doSomethingWith(this.responseText);
}
};
xhttp.open("GET", "http://url/file.csv", true);
xhttp.send();
You could also use jQuery's ajax function :
$.ajax({url: "http://url/file.csv", success: function(result){
doSomethingWith(result);
}});
This way, you get the result as a string which you can then use to retrieve the CSV values - look into the split function for instance.
Be aware that you will not be able to try this locally without a webserver, since your browser will not allow your Javascript to fetch files from your computer. Indeed, your browser implements a mechanism called CORS which restricts HTTP requests heading to a different domain.
Did you publish that .csv to google ? If so , can you program the file to be dumped to your web-content file?
I found I couldn't get files out of google drive with js, a lot of people had problems with this, then I tried to find a solution for it. So instead you can use platforms like github, or host on your server. Then the problem becomes way more straight forward.
I used python to grab the content I wanted , turn into .js file, or json file. Then use javascript to retrieve it.
var data = http://mywebsite.com/my_file.json
or script src = http://my_website/data.js /script
Sorry about the above. Stackoverflow messing with my js. The above is just an example of the script tag 'my_website' needs to be programmes in.
Great place to start with json , and other resource here
https://www.w3schools.com/js/js_json_intro.asp

Javascript: Save uploaded file

I would like to save uploaded file using javascript, in my linux server. The code I wrote is:
if (uploadInput.files.length == 0) {
console.log("No file is uploaded. ");
} else {
console.log("File uploaded.");
var file = uploadInput.files[0];
}
Now I would like to save that file as "files/upload.csv". Can anyone please advise, how can I do it?
Thanks in advance
What I'm going to do is walk you through the logic, instead of providing code. There is just not enough information here on what you want to do to provide actual code and the sample you provided is a very small part of what the actual solution would need to include.
I'm assuming the code you wrote above is meant to run on a website visitor's browser (client-side). Client-side code can't save to a server. What it can do, is send the file contents to the server. But then you'd need something on the server side to process that file contents and actually save it to the server-side files directory.
One method to send the file contents from the client to the server is to use AJAX - you can do this with native javascript, but I would recommend looking into a library such as Jquery, which makes it a lot easier. See http://api.jquery.com/jquery.ajax/ This AJAX code will need a communication point on the server to send the file contents to. From your profile it seems you're familiar with PHP. You could make a php file on the server (say receivefilecontents.php) that takes in input from that client-side AJAX call, and then saves it to a server directory - you could also do this in Python, Java or a number of other languages.

Saving a text file on server using JavaScript

Is it possible to save text to a new text file using JavaScript/jQuery without using PHP? The text I'm trying to save may contain HTML entities, JS, HTML, CSS and PHP scripts that I don't want to escape or use urlencode!
If it's only can be achieved using PHP how can I pass the text to PHP without encoding it?
You must have a server-side script to handle your request, it can't be done using javascript.
To send raw data without URIencoding or escaping special characters to the php and save it as new txt file you can send ajax request using post method and FormData like:
JS:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
PHP:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
Edit:
As Florian mentioned below, the XHR fallback is not required since FormData is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:
var xhr = new XMLHttpRequest();
Also please note that this works only for browsers that support FormData such as IE +10.
It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.
However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:
http://api.jquery.com/jQuery.post/
And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!
File uploading (most of this applies if sending plain text too if javascript can choose the name of the file)
http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security
https://www.owasp.org/index.php/Unrestricted_File_Upload
If you still want to work in JavaScript and avoid PHP, CGI, and things like that, it's no longer true that you can't do server side scripts with JavaScript.
With Node.js, you can do server side JavaScript. Of course, you have to have a server than can run a Node.js server. But once you get it up and running, you can write the server script to accept a JSON formatted string from your client side scripts Then, based on that JSON string received, the server side script could create and save files. Of course, you want to make sure you write secure code, check what is being sent to your server and verify it's not malicious before creating the files and saving them. You also probably want to stagger timing and pause between files to ensure you're not susceptible to a DDOS attack, either.

How to transfer variable data from Python to Javascript without a web server?

I'm working on automatically generating a local HTML file, and all the relevant data that I need is in a Python script. Without a web server in place, I'm not sure how to proceed, because otherwise I think an AJAX/json solution would be possible.
Basically in python I have a few list and dictionary objects that I need to use to create graphs using javascript and HTML. One solution I have (which really sucks) is to literally write HTML/JS from within Python using strings, and then save to a file.
What else could I do here? I'm pretty sure Javascript doesn't have file I/O capabilities.
Thanks.
You just need to get the data you have in your python code into a form readable by your javascript, right?
Why not just take the data structure, convert it to JSON, and then write a .js file that your .html file includes that is simply var data = { json: "object here" };
What do you thing about using some Templating system? It will fit your needs.
I know you've specifically mentioned "without a web-server", but unless you want to really go out of your way, and over-complicate this, and restrict flexibility for future use:-
Could you not use a very simple webserver such as: http://docs.python.org/library/simplehttpserver.html ? That way, should you need to expose the site, you've got the URL's already in place to set-up a proper webserver.
Maybe you could write to a cookie and then access that via JavaScript? Similar to this SO answer here?
You could use Python's JSON Encoder and Decoder library. This way you could encode your Python data into JSON format and include that in your HTML document. You would then use Javascript in the HTML file to work with the JSON encoded data.
http://docs.python.org/library/json.html
If this only needs to be for localhost, you could do something like the following.
To access, you would make a call to http://localhost:8080/foo; this can cause some issues due to Cross Site Injection Protection, however; these are readily solved by Googling around.
On the JS side, you would make an AJAX call like this (assuming jQuery)
$.ajax('http://localhost:8080/foo', function (data) {console.log(data)});
And then on the Python side you would have this file in the same directory as the html file you are seeking to use (index.html) on your computer, and execute it.
import BaseHTTPServer
import json
class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
desiredDict = {'something':'sent to JS'}
if self.path == '/foo':
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(desiredDict))
else:
if self.path == '/index.html' or self.path == '/':
htmlFile = open('index.html', 'rb')
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Access-Control-Allow-Origin","http://localhost:8080/")
self.end_headers()
self.wfile.write(htmlFile.read())
else:
self.send_error(404)
server = BaseHTTPServer.HTTPServer(('',8080), WebRequestHandler)
server.serve_forever()

how to load xml data from server in client side using javascript or vbscript?

It's been almost three weeks and I'm Googling around. my eyes got tired and headaches was included too.
I couldn't do it what even 8-10 hours daily computing :(
I have some data that saved in a valid XML file on the server(domain or sub-domain)
I've choosed XML because I'm may or probably need it for other future application use.
What I want to do is:
1- including the XML file and load it on a client side HTML page.(does sub-domain or normal domain make a difference while including?)
2- I do prefer using JavaScript (or Vb Script) or any other client side script(if available) for parsing or manipulating thing.
And If you do prefer me a better way to include a server side XML file including....I'm listening
EDIT:
I'm working on AJAX now but why I can't get data from a URL?
something like:
xmlhttp.open("GET","https://www.mywebsite.com/xmlfile.xml",true);
buy it's not working :(
Because you haven't given the actual code that you're using, I am guessing here and have put together an HTA that you can try. This only works on Windows (as I believe that is the platform you're targeting). Copy this code into a text file and save it with a .hta file extension:
<html>
<head>
<title>HTA Ajax Example</title>
<script type="text/javascript">
var ajaxRequest = function() {
var http = new ActiveXObject('MSXML2.XMLHTTP');
http.onreadystatechange = function() {
if(http.readyState === 4 && http.status === 200) {
var div = document.getElementById('target-div');
div.innerHTML = http.responseText;
}
}
http.open('GET', 'http://www.w3schools.com/ajax/ajax_info.txt', true);
http.send();
return true;
}
</script>
</head>
<body>
<div id="target-div"></div>
<input type="button" value="load" onclick="ajaxRequest();"></input>
</body>
</html>
On clicking the Load button, the text from your w3schools example will be loaded into the page. This should get you started. Should you want to provide a cross-platform solution, a library like jQuery will handle all the differences for you.
As mentioned before, the url used in the request is a full url to a resource on a different server. This won't work if you put this code on a server because of the cross-domain security issue.
If you want to pick up information from an XML file, you might want to use http.responseXML rather than http.responseText. The former property makes the response available as an XML document object rather than a text string.
including the xml file and load it on a client side html page.
Use Ajax, and use a library to access it.
does sub-domain or normal domain make a difference while including?
If it is different to the page: yes
Can you use AJAX? http://www.w3schools.com/ajax/default.asp

Categories

Resources