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.
Related
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
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.
In our application we need to implement following scenario:
A request is send from client
Server handles the request and generates file
Server returns file in response
Client browser displays file download popup dialog and allows user to download the file
Our application is ajax based application, so it would be very easy and convenient for us to send ajax request (like using jquery.ajax() function).
But after googilng, it turned out that file downloading is possible only when using non-ajax POST request (like described in this popular SO thread). So we needed to implement uglier and more complex solution that required building HTML structure of form with nested hidden fields.
Could someone explain in simple words why is that ajax requests cannot be used to download file? What's the mechanics behind that?
It's not about AJAX. You can download a file with AJAX, of course. However the file will be kept in memory, i.e. you cannot save file to disk. This is because JavaScript cannot interact with disk. That would be a serious security issue and it is blocked in all major browsers.
This can be done using the new HTML5 feature called Blob. There is a library FileSaver.js that can be utilized as a wrapper on top of that feature.
That's the same question I'd asked myself two days ago. There was a project with client written using ExtJS and server side realisation was on ASP.Net. I have to translate server side to Java. There was a function to download an XML file, that server generates after Ajax request from the client. We all know, that it's impossible to download file after Ajax request, just to store it in memory. But ... in the original application browser shows usual dialog with options open, save and cancel downloading. ASP.Net somehow changed the standard behaviour... It takes me two day to to prove again - there is no way to download file by request usual way ... the only exception is ASP.Net... Here is ASP.Net code
public static void WriteFileToResponse(byte[] fileData, string fileName)
{
var response = HttpContext.Current.Response;
var returnFilename = Path.GetFileName(fileName);
var headerValue = String.Format("attachment; filename={0}",
HttpUtility.UrlPathEncode(
String.IsNullOrEmpty(returnFilename)
? "attachment" : returnFilename));
response.AddHeader("content-disposition", headerValue);
response.ContentType = "application/octet-stream";
response.AddHeader("Pragma", "public");
var utf8 = Encoding.UTF8;
response.Charset = utf8.HeaderName;
response.ContentEncoding = utf8;
response.Flush();
response.BinaryWrite(fileData);
response.Flush();
response.Close();
}
This method was called from WebMethod, that, in turn, was called from ExtJS.Ajax.request. That's the magic. What's to me, I've ended with servlet and hidden iframe...
you can do this by using hidden iframe in your download page
just set the src of the hidden ifame in your ajax success responce and your task is done...
$.ajax({
type: 'GET',
url: './page.php',
data: $("#myform").serialize(),
success: function (data) {
$("#middle").attr('src','url');
},
});
Currently I use this code to read a txt file with words and perform some operations. However, this particular code requires the html to be deployed on a server. Is there any workaround where I can replace this code with something else to read the file without the need of a server?
var xhr = new XMLHttpRequest();
xhr.open( "GET", "dictionary.txt", false );
xhr.send( null );
var words= xhr.responseText.split(",");
It is NOT possible to call Ajax outside your server domain (except you use scriptagproxy, that too requires you to have some server side configuration). So, in short, you CANNOT read files on your local computer using Ajax calls.
You might like this article.
The file selection can be made either by input or drag-and-drop (not otherwise). Please see: this
You cannot read files from the clients' computer, so the text file you are reading must be on the same server as your javascript.
However, if you are loading the HTML file from your computer (e.g. file://c:/../test.html), you might be able to read files located on ONLY your computer by using relative paths.
You can hide an iframe on the page, with its src='dictionary.txt',
and read or manipulate the iframe's local content when it's onload event fires.
My project requires me to add a "SaveAs PDF" feature. I was looking for a pure JavaScript solution which does this just in client end, however, was told that it's not implementable, at least for now.
jsPDF currently is still a limited version, not support graph and others. So now I am looking for a stable open-srouce free solution to set up a server web service, that receive data from client-end and send back the produced PDF file or a link for user to save to their disk.
The data from client is determined by client user, which means, not the whole page. User can choose to save a map, a table, or all of them into PDF file.
Any recommendations?
PS: in Windows environment
You might check out the ReportLab Toolkit - it includes an Open Source Python library for creating PDFs. (You didn't specify what server-side language you wanted, but Python is pretty widely supported.)
If you need something that can be coded in Javascript, one option might be PhantomJS. This tool allows you to run a headless Webkit browser from the command line, and among other things it can render and save webpages as PDFs. Slippy uses this approach, so you might be able to get example code from that project. Scripting the PDF creation would probably be much faster in PhantomJS than in Python, but it's likely to be much slower (it has to fire up a Webkit instance) and server installation might be complicated.
I've create this function in javascript which send on iframe to the server:
function download(url, datas){
if(url && datas){
var inputs = '', value,
iframe = '<iframe name="iframeDownload" id="iframeDownload" width=0 height=0></iframe>';
$(iframe).appendTo('body');
datas.forEach(function(data){
name = encodeURI(data.get('name'));
value = encodeURI(data.get('value'));
inputs+='<input name="'+name+'" value="'+value+'"/>';
});
$('<form action="'+url+'" method="post" target="iframeDownload">'+inputs+'</form>').appendTo('body').submit().remove(); // .appendTo and remove() are needed for firefox
$(iframe).remove();
};
};
I'm encoding the input name and value to be able to send data.
On my server, I'm using php, so to decode this, you need: rawurldecode. If you define the name of the inputs as "fileName" and "file" you can write this:
$fileName = rawurldecode($_POST['fileName']);
$file = rawurldecode($_POST['file']);
After than, to force the download, you need to send the corrects header. I'm using this function:
function download($filename, $file) {
header('Content-disposition: attachment; filename="'.$filename.'"');
header('Content-Type: application/force-download');
header('Content-Length: '. filesize($file));
readfile($file);
}
If you don't need to send the file from javascript because it's created on the server side, just add the path of your file to the download function.
If you're using PHP, You can use fpdf to generate the pdf.