to send a text file to server using javascript - javascript

I need to send a text file to server and get it saved. how can i do it using javascript???

There are all sorts of security issues surrounding this. Would you be happy to visit a website that would upload a file from your machine to the server?
For a generic website, where users are likely to have their permissions set to deny this sort of access it isn't possible.
If by chance, you are looking to do this for an application where you have control over the security settings for its users, and that you can guarantee its Windows and IE, then it is possible by reading the file and passing the details by posting to the server. See the following link : http://www.javascripter.net/faq/reading2.htm
However when you move away from IE or Windows, then you are going to struggle.

using ajax of course.
have a file on the server, PHP or ASP - depending on what your internet server is.
this file will accept the text file (data and name), and should also check for size and if this file already exists or not, and if all is ok- it will save it, and return a string "OK"
on the client, javascript side, just send the information to the server using ajax, or HTTPREQUST object - there's plentty of documentation for that around. and if you get back a response of "OK" then you know that it sent well.
even better: don't use HTTPREQUEST, but do dynmaic script tag insertion - where the source attribute of the script you're appending is that file on the server like:
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = "http://server/serverFile.PHP?filename=XXX&data=LONG STRING OF DATA REPRESTING THE DATA TO BE SAVED PROBABLY LESS THAN 2K IN SIZE AND ALSO YOU SHOULD ESCAPE OR ATLEAST URIENCODE IT";
document.body.appendChild(a);
and on the server file, serverFILE.PHP:
<?php
// some code to save the request variable [data].
// if all is ok:
alert("ok")
// or:
result = "ok"
?>
get it?
note: you'll probably have a limit of less than 2K on the file size.

Javascript is a front-end language. You may use php or any server side language.

You can create an Ajax equiv function make an iframe with width and height=0px then make it the target of the form with the file upload input and process it with the action PHP
<form action="upload.php" target="target" method="post"
name="uploadform" id="uploadform" enctype="multipart/form-data">
<label for="input_file_upload">Upload:</label>
<input onchange="document.uploadform.submit();" size="80"
type="file" name="file_upload[]" id="file_upload"
multiple="multiple" />
<input type="hidden" name="fileUpload" value="upload" />
<input type="button" value="Upload" />
</form>
<iframe id="target" name="target" style="width: 0px; height: 0px;">
</iframe>

Related

Saving User Output to a Text file

I am wanting to save user input to a text file that will be stored in my local folder directory with filename as date-time(hh-mm-ss).txt So once the user clicks the "save: button, it'll save the contents to that date-time(hh-mm-ss).txt file
I am learning, so please show me with a little explanation, thank you
Current html:
<form>
Subject:
<input type="text" id="subject" size="20">
<br>
Description:
<textarea id="newDescription" rows="4" cols="50" required spellcheck="true"></textarea>
<br>
Tags:
<input type="text" id="tags" size="20">
<br>
<input type="button" value="Save"
onclick="addDescription(this.form);">
</form>
Current external JS:
// This function accepts user input.
function addDescription(form) {
document.getElementById("info").innerHTML =
form.elements["subject"].value + "<br>" +
form.elements["newDescription"].value + "<br>" +
form.elements["tags"].value + ".";
form.reset();
form.elements["subject"].value
form.elements["newDescription"].value
form.elements["tags"].value;
} // end addDescription
Also, if anyone has a better idea on how to make the appearance of the portion of the html look better on the webpage because as of now the label and text boxes look crushed together!
JavaScript on the client side (in the browser) can't read or write files (imagine how dangerous that would be?).
To write a file you'd need server side technology such as NodeJS (if you want to stick with JS). The client side will need to send the data to your backend (NodeJS).
Instead of giving you copy & paste code, I'll give you direction on how to approach the problem, and resources that will get you there:
Set up a backend with NodeJS. Easiest is to use Express:
https://expressjs.com/
To write files with your backend you can use plain NodeJS. Learn
how to do that here.
Build your form correctly by learning from boilerplate code. A good
framework for building out neat HTML and CSS might be Bootstrap,
or Tailwind.
Post the user's data to your NodeJS backend from your form using the
fetch API.

Including imagegrabscreen php function to a button onclick without refreshing the page

I'm trying to create a button with an onclick function that activates the imggrabscreen php function. Problem is, I've done several codes and so far the only function that I was able to use was a submit input type in which this refreshes the page. I tried using button as an input type but unfortunately, it does not save any screenshots upon clicking the button. Here's the code that I'm using so far.
if(isset($_POST['btnscreen']))
{
$im = imagegrabscreen();
imagepng($im, "screenshot.png");
}
ob_end_flush();
?>
<form method="post" action="" enctype="multipart/form-data">
<br>
<input type="submit" value="Click to Screenshot" id="btnscreen" name="btnscreen"></center>
<br><br>
</form>
php is parsed and executed server side (pre-processing) so you cannot call any php functions after the page has been sent to the browser. The only way to do this is to make a new request to the server (ajax).
I can't quite grasp what your function does (php cannot make a screenshot of what your browser is displaying as it has no information of how it has been rendered - please note different browsers may display the page differently).
I would try reading up on html5 canvas element which can achieve that (e.g. https://html2canvas.hertzen.com/).
Hope this helps

How to parse CSV file and store it's data into database?

I trying to store CSV data to database using onclick function. Unfortunately, I am using php code inside javascript function which is not efficient enough. Therefore, I hope that I can get any suggest or solution to improve efficiency of my project by using javascript instead of php to store CSV data into database.
This is javascript with php code :
<script>
function storeQueEmail(){
<?php
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
$record['contact_first'] = $data[0];
$record['contact_last'] = $data[1];
$record['contact_email'] = $data[2];
$record['subject'] = $_REQUEST['subject'];
$record['message'] = $_REQUEST['message'];
$record['status'] = 0;
$oAdminEmail->insertQueEmail($record);
}
} while ($data = fgetcsv($handle,1000,",","'"));
?>
}
</script>
This is HTML code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" >
Subject : <br/>
<input type="text" name="subject" id="subject" required/> <br/>
Choose your upload type: <br />
<input name="csv" type="file" id="csv" accept=".csv" required/> <br/>
Content : <br/>
<textarea name="message" cols="50" rows="10" required></textarea><br/>
<input type="submit" name="submit" value="Submit" onclick="storeQueEmail()"/>
</form>
</body>
</html>
what are you trying to do there? I think you are speaking about a PHP in
HTML document. So your PHP code inside your function is interpreted on server. As your PHP code has no output your Javascript function is simply empty. Thus as you have registered your Javascript function as onclick handler just nothing would happen.
Remember that standard Javascript code is interpreted on Client (that means in browser) though you PHP code is interpreted on server. As mentioned in the comments above it is possible to use an AJAX or POST/GET - Request to send data to your server and then write it to your DB or file etc.
Another way to do this directly with Javascript is Node.js - serverside Javascript that is able to write to your Database like PHP can do.
The easiest way for you to do it with your HTML code you presented above is to fill in your
action - attribute
in your
form tag
For example:
<form action="proccessData.php" ...>
...
</form>
Don't forget to remove your onclick - attribute inside form's submit input field.
If you know press your submit button your entire form and its content will be send to http://www.xyz.de/proccessData.php. Inside that file you can work with your form data: In your case two text fields and one file upload field. As you may know you could get to the content of text input field send via post via:
$_POST['<name of field>']
To get your uploaded file and proccess it you could use PHP's global
$_FILE[] - Array
Just refer to PHP's manual on php.net or some other online documentation. There's pretty much to find on the web.
I just give you a helpful link to php.net on how to handle file uploads in a correct and therefor secure manner: http://us2.php.net/manual/en/features.file-upload.php
Once you have read your uploaded file via PHP's global $_FILE[] - array just proccess that file via fgetcsv in your proccessData.php and write it line for line to your database.
Hope that helps! It is really not that hard :)

Why does my form post function opens my .pl file instead executing it?

I have a PERL script download.pl which should be executed when a button is pressed. It is used to download an SVG.
But when the button is pressed, the website shows me the content of the perl script instead of executing it. Why is this and how do I fix it?
This code is what is called when I press my button:
function callOnButtonClick(){
var svg = document.getElementById("mainSVG");
// Extract the data as SVG text string
var svg_xml = (new XMLSerializer).serializeToString(svg);
console.log(svg_xml);
var form = document.getElementById("svgform");
form['output_format'].value = "svg";
form['data'].value = svg_xml ;
form.submit();
}
This is the form I use to execute my download.pl file which should initiate a download.
<form id="svgform" method="post" action="download.pl">
<input type="hidden" id="output_format" name="output_format" value="">
<input type="hidden" id="data" name="data" value="">
</form>
This is a problem of configuration of your web server. It seems it is not aware that it should execute perl scripts and return the response, rather than just serve the file.
Have a look at the documentation of your web server to see how to configure it to execute perl scripts, or post more information about your server and what you have tried if you already have configured your server but it does not work.
Edit your httpd.conf.
You should replace your part with below. Replace X with your directory.
<Directory "X:\webserver\cgi-bin" />
AddHandler cgi-script .cgi .pl
Options FollowSymLinks +ExecCGI
AllowOverride None
</Directory>

Simplest way for image upload function , without refreshing page

Here's a challenge:
I don't care about which language to use, Javascript, PHP, .. whatever.
I need the most simple way to let my user upload an image.
I will later offer the user a way to place it on a canvas (displayed inside a div, with jquery draggable)
I can not have the page refreshed since there are useful variables in other fields etc..
(I don't have any security preferences as this will be a local website for intranet)
I tried:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
</br>
<input type="file" name="file" id="file" size="70%"><br>
</br>
<input type="submit" name="submit" value="Submit">
</form>
But then came to realise there are soo many options out there, such as uploadify, and i easily got lost online..
You have two choices to make a file upload w/o refreshing the page:
Use HTML5 form upload
Post the form to an hidden iframe
The latter one gives best browser compatibility, and is what I'd suggest you to use. To post to an hidden iframe, simply set the target of the form to the iframe:
<script>
// Global callback function from the file
function uploadCallback(){
console.log("File is uploaded!");
}
</script>
<iframe name="hiddentarget" style="display:none;"></iframe>
<form action="upload_file.php" method="post" enctype="multipart/form-data" target="hiddentarget">
...
To respond back to the site from the iframe, you will have to go through the window.top frame as such:
upload_file.php:
<?php
// Uploading stuff
// ...
// "Talk" back to the site
// Of course you can (should) pass some parameter to this JS-function, like the filename of the recently uploaded image.
echo "<script>window.top.uploadCallback();</script>";
?>
EDIT:
As suggested by other users; the optimal solution would be to use the File API where supported, and fall back to the hidden iframe on browser that doesn't support it. This gives you nice features such as file uploda progress for example.
The way that I would suggest is using AJAX and and make your upload box a div which can be replaced when the upload is successful. Instead of traditional post you then create a Javascript function for onSubmit. Your action can then be changed to #.
If you lookup AJAX there are some great tutorials about and you will be able to do many more amazing things.
Alternatively look into jQuery which will definitely have something to help you
I'm gonna show you an example on how to use the jQuery Form Plugin to upload files to your server really easy without needing to refresh the page.
First off, download and install the jQuery Form Plugin. After you do that, include it in your files where you want to make use of it. Add an ID attribute to your form tag like this:
id="unique_id"
After you have identified the upload form, put this code in your jQuery:
$(function() {
$('#unique_id').ajaxForm({
target: '.myTarget' // Display here whatever the server side script returns
success: function(response) {
// An usual success callback
}
})
})
Assuming that your server side language is PHP, this is how a simple upload script would look like (upload_file.php):
<?php
$uploaddir = 'your_upload_dir/something';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']); // Filename
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo $uploadfile;
} else {
echo "Error";
}
?>
Where userfile is the name attribute of your file input (<input type="file" />).
The above code combined returns the relative path to your image which you can use to display the image inside an img tag. You must use Javascript (or jQuery) for that.

Categories