Writiing to a SERVER file using JS - javascript

Tried all solutions.. none of them seem to work for me.
Basically, I have this website UPLOADED on the server that has a button which when clicked does a simple task of loading a file from the server, displaying it and adding +1 to it and then saving it back.
The main question now arises, I tried all the ways which I could find on the net to save the file back but it doesn't seem to work for me. Any specific advice on how can I fix this issue using JS?
UPDATE - One way I am using is - (Doesn't work tho)
fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("TOTAL.TXT", true);
var text = test1;
s.WriteLine(text);
s.Close();
Where test1 is the name of the variable which i am trying to write.

assuming that you have php on server try this js
var data = new FormData();
data.append("data" , 1);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
php script
<?php
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "filname.txt"
$file = fopen("upload_or_whatever_path/" .$fname, 'w') or die("Unable to open file!");// open file
fwrite($file, $data);
fclose($file);
}
?>

The code you've shared belongs to the Windows Scripting Host platform. That's an automation solution for Microsoft Windows that's by no means intended for public web sites.
File upload implementation requires a proper server-side programming language (PHP, JSP, Node...). Client side code can be as simple as a static HTML form.

Related

PHP web page work with WAMP but fails on GoDaddy

I am developing a web page using HTML, PHP and Javascript. I am using aWAMP server to develop on my local machine. It has one PHP function:
<?php
$file = fopen("Records.txt","r");
$line = fgets($file);
fclose($file);
?>
It has one line of code within the Javascript portion to retrieve $line:
let fullstring = <?php echo json_encode($line); ?>;
It works fine using WAMP. If I view the source I see that the above line is:
let fullstring = "Record1,Record2,Record3,Record4,Record5,Record6";
I then uploaded the file to GoDaddy and it fails. I see this instead:
let fullstring = false;
Anyone know why? Is there a different way to retrieve a PHP variable via Javascript? Eventually I need to change this because the variable $line value should not be exposed to the user.

Saving a file to server using PHP and JS?

I have been trying this for a few hours now, googling around and trying several approaches. The code is so simple I don't understand why it doesn't work. I am using 000webhost free hosting atm just to test this out.
I literally just wanna pass a variable to the php file for it to save in a text file, in this case "ayy".
Latest code (file does not even get created):
JS Code
function doSave(){
xhr.open("POST", "save.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send("ayy");
}
PHP code (save.php)
<?php
file_put_contents('data.txt', file_get_contents('php://input'));
?>
I did also have this code below earlier, however it only created a blank file and would not append any text to it:
index.htm
function doSave(){
var datastr = "ayy";
var xmlhttp = new XMLHttpRequest();
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.open("GET", "save.php", true);
xmlhttp.send(datastr);
}
save.php
<?php
$post_data = $_POST['datastr'];
$f = fopen("data.txt", "w+");
fwrite($f, $post_data);
fclose($f);
?>
Any suggestions why this might not be working? All I can think of is the server not supporting it or something, however I can get it working fine if I specify the variable IN the php file and using a GET request to simply just post the variable. However the data is going to be dynamic so I need to pass it from client-side using js.
Thanks.

php canvas to image on server

I want to take the image data from my canvas on the client and save it as a .png on my server.
This is the code on my client that gets the image data from the canvas and sends it to saveImage.php:
function render()
{
var imageData = ctx.canvas.toDataURL("image/png");
var postData = "imageData="+imageData;
var ajax = new XMLHttpRequest();
ajax.open("POST","saveImage.php",true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.onreadystatechange=function()
{
console.log(ajax.responseText);
}
ajax.send(postData);
}
And this is what saveImage.php looks like:
<?php
if(isset($_POST["imageData"]))
{
$imageEncoded = $_POST["imageData"];
$imageDataExploded = explode(',', $imageEncoded);
$imageDecoded = base64_decode($imageDataExploded[1]);
$filename = time()."image".mt_rand();
$file = fopen("./".$filename.".png","wb");
fwrite($file, $imageDecoded);
fclose($file);
echo $filename;
exit();
}
?>
The code actually works fine, my problem is just that the images that gets created are faulty in some way.
When I try to open one, windows says that it cant show me the image because it doesn't support the format? even though its a .png?
what am I doing wrong here?
You should be encoding your data with encodeURIComponent() before including it in POST data.
You should also be using a framework like jQuery to account for browser differences. I guarantee that code will not work the same in all browsers.
On the PHP, try looking into file_put_contents() for writing data. Much quicker to type!
Have you checked what is actually being sent over HTTP? $imageEncoded probably starts with data:image/png;base64,xxxxx
Strip everything up to the comma after base64:
https://stackoverflow.com/a/15153931/3766670

Storing the names of all files with a certain extension in a folder in a string?

I have a folder on my webserver to which I, using a form and a PHP script allow people to upload files. I then need to use these files (xml-files) in another script. This means that I need the script to, everytime it is loaded, find all files of the extension .xml and store their names in an array.
Is this possible using Javascript (this is preferred since the script that needs all filenames is written in Javascript)? Otherwise, what is the best solution?
Thanks for any help!
Finally managed to solve it. Heres my PHP script:
<?php
$files = array();
foreach (glob("../pathtofolder/*.xml") as $file) {
$files[] = str_replace("../guide/", "", $file);
}
echo json_encode($files);
?>
This is "sent" to the javascript using an XMLHttpRequest:
var oReq = new XMLHttpRequest();
oReq.onload = function() {
var files = JSON.parse(this.responseText);
};
oReq.open("get", "phpscript.php", true);
oReq.send();
The variable files now contains all filenames!

Downloading files using Header with a JS input

I have a page that has a JavaScript function that uses Post to send a variable to a php file. The problem is, that I am using "header" to download the file and my JS does not open the PHP script in a new page.
When I open the php file in a new page, it does not receive the needed variable from the JS.
I know it sounds confusing, but I hope my code can shed some light on my problem.
The short version is, I am trying to download a file that is selected by a radiobutton. I use JS to check which radiobutton is checked and then send that to my php file. Which then needs to download the file.
Thank you all in advance.
PHP:
<?php
if (isset($_POST['routenumber'])) {
if(!isset($_SESSION)){session_start();}
$routenumber = (isset($_POST['routenumber']) ? $_POST['routenumber'] : null);
$directory = ("Users/".$_SESSION['id']."/SavedRoutes/");
$routes = scandir($directory);
sort($routes);
$route = $routes[$routenumber];
$file =("Users/".$_SESSION['id']."/SavedRoutes/".$route);
header("Content-type: application/gpx+xml");
// header("Content-Disposition: attachment;Filename=".json_encode($route).".gpx");
header("Content-Disposition: attachment;Filename=route.gpx");
readfile($file);
}
?>
JS:
function fuAccountDownloadRoute(){
var i=2;
var SelectedRadio
while (i < routecounter){
var str1='radio';
var str2=JSON.stringify(i);
var result = str1.concat(str2);
if (document.getElementById(result).checked){
SelectedRadio = result.slice(5);
}
i=i+1;
}
$.post('accountPage.php',{routenumber:SelectedRadio});
}
When you open the url: http://localhost/accountPage.php in your browser it makes a GET request. You should change all the $_POST to $_GET in your code if you want to make it possible, and then you can open it like this: http://localhost/accountPage.php?routenumber=3, though it's probably not what you really want.

Categories