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.
Related
Edit: Update - Solution
So I have achieved what I needed to do: Write data to file on the server. I am not exactly sure how things work but it seems that:
xhttp.send(data);
does not send all the data in a FormData variable but rather only the data with the "key" "data". (Sorry if I have the terminology wrong here.) So what I did is I took my object "userData" and applied the following:
userStringData = JSON.stringify(userData);
I then put the userStringData into a FormData variable as follows:
var data = new FormData();
data.append("data" , userStringData);
This then successfully wrote to the file on the sever. In the file I only had userStringData and not the "key" "data".
In my PHP file I also included a new line after every write so that each userString data would be on a new line:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "users.txt";
$file = fopen("./AJG_Data/".$fname, 'a');
fwrite($file, $data);
fwrite($file, "\r\n");
fclose($file);
So this is working for me now. Thanks to those who offered advice and assistance.
Edit: Update:
Objective: To write data to the server using AJAX and PHP. (Please refer to original question below if necessary)
Thanks to ADyson's comments I have made a lot of progress. I have learnt that an XMHHttprequest is the way to make an AJAX request to the server. I have this code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let successString = `Thank you ${userData.athlete.firstname} you have successfully granted permission to read your data.`
document.querySelector("#message-0").innerHTML = successString;
}
};
xhttp.open("POST","/path_to_my_php_file/file_write.php", true);
xhttp.send(data);
}
On the server side I have this in my php file:
<?php
$dir = 'AJG_Data';
// create new directory with 744 permissions if it does not exist yet
// owner will be the user/group the PHP script is run under
if ( !file_exists($dir) ) {
mkdir ($dir, 0744);
}
file_put_contents ($dir.'/test1.txt', 'Hello File');
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "users.txt";
$file = fopen("./AJG_Data/".$fname, 'w');
fwrite($file, $data);
fclose($file);
}
?>
The directory creation section above is not necessary it was part of my trouble shooting.
The above works perfectly if I send simple FormData created as follows:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
The problem I have is that when I try to send more complex FormData. It doesn't work. It doesn't recognise my FormData and it doesn't get past this if statement:
if(!empty($_POST['data']))
I have checked my FormData using this code:
for (var pair of data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
The above code returns the following:
token_type, Bearer
expires_at, 12345678910
expires_in, 1234
refresh_token, 1234567890abcefg...
access_token, 1234567890abcdefg...
athlete[id], 1234567
athlete[username], joe_soap
athelete[resouce_state], 2
athlete[firstname], Joe
...
...
athelete[created_at], 2017,01-03T16:07:37Z
...
...
athlete[profile], https://some.web.address/larg.jpg
So as far as I can tell I have good FormData but nothing gets written on the server side.
How can I correct this?
Thank you.
The original question follows below.
I have successfully retrieved data from the Strava API using JavaScript code. I have the data stored in a variable as a JavaScript object. I want to write the data to a file on the server.
I have spent hours searching the web and I can't find a solution. It seems this may be possible using ajax or jQuery but I can't find a simple step by step explanation of how to do this.
Bottom line: I want a simple way to write data to file on the server using JavaScript or something related to JavaScript that is quick and easy to implement. Assuming I can successfully write to file I will later want to read from file.
You would need another file on the back end, which would actually do the writing. I'll assume PHP. I'd recommend base64 encoding the data, and storing it encoded to save time.
Javascript:
if (window.XMLHTTPRequest) {
var xhttp = new XMLHTTPRequest();
} else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Process output, get result text with this.responseText, decode base64, and parse JSON
alert(JSON.parse(window.atob(this.responseText)));
}
}
xhttp.open("POST", "file-load.php?key=" + window.btoa(JSON.stringify(value)), true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send();
PHP:
<?php
$key = $_POST['key'];
file_put_contents("storage.txt", $key); //Set file contents
Or, if you want to append it:
<?php
$key = $_POST['key'];
$current = file_get_contents("storage.txt");
file_put_contents("storage.txt", $current . "\n" . $key);
To read the file, just use the same setup as before for javascript, but instead of file-load.php, use file-read.php:
echo file_get_contents("storage.txt");
Use the onreadystatechange to read the output.
My Problem
So I have been trying to create a simple file upload system using JavaScript (XHR) and PHP, and I have come across a problem where once the file has been uploaded to the PHP handler, it always returns that $_FILES is not set.
Code
JavaScript (on the server www.example.com):
var file = document.getElementById("fileInput").files[0];
var formData = new FormData();
formData.append("track", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "//handle.example.com/uploads.php", true);
xhr.onload = function(){
if(xhr.status == 200)
// awesome, it worked
else
return console.error("Something went wrong.");
};
xhr.send(formData);
PHP (on the server handle.example.com):
header("Access-Control-Allow-Origin: http://www.example.com", false);
if(isset($_FILES["track"])){
$file = $_FILES["track"];
$fileTemp = $file["tmp_name"];
$fileSize = filesize($fileTemp);
if($fileSize <= 150000000)
$data = "Success"; // this is returned if a file is an image file
} else
$data = "File not set."; // this is returned if a file is an audio file
echo $data;
exit;
HTML (on the server www.example.com):
<form method="post" enctype="multipart/form-data" id="ulF_uF1">
<input type="file" name="file" accept="audio/x-aiff,audio/flac,audio/mpeg,audio/ogg,audio/wav" id="fileInput">
</form>
What I've Tried
Setting the upload_max_filesize and post_max_size to 150M and 151M respectively.
Changing the name of the field name
Changing $_FILES to $_POST
None of this has worked for me, and I can't seem to find another other viable solutions relating to my problem, so all help is appreciated.
UPDATE:
After some careful testing, I realised that my upload script is actually working perfectly. What it doesn't like is the file types that are being uploaded. For some reason, PHP (version 7.2.1 at least) does not like when I upload audio files; uploading image files or PDF's work fine.
xhr.setRequestHeader("Content-Type", "multipart/form-data");
The Content-Type header for a request formatted as multipart/form-data must include a boundary parameter to tell the recipient of the message where each new bit of data starts.
By manually providing the header without it, you make the request unparsable.
Remove that line. Allow XMLHttpRequest to generate the correct content-type header for you using the FormData object.
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.
I have this code that I want to use to pass information to a php file:
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "page.php?sess=123123", true);
xhttp.overrideMimeType('text/xml; charset=UTF-8');
xhttp.send(null);
</script>
If i echo this code in my .php page, it works on page load ("page.php" recieves the sess variable and stores it). However, when I copy this code (without the script tag) into a .js file that I use in my main php page, it doesn't work.
The idea is that I want to pass sess parameter to page.php when a specific javascript based timer is triggered.
Your help is appreciated.
All I'm trying to do is send a string, in html, to a script written in PHP. I've tried several solutions, including making an html element and putting it in a form and then passing the form (didn't work). I don't know the basics of AJAX or PHP, everything is just kind of being pieced together via what I can google. Here's one way I trying to remedy the situation: (The regexp replaces the first line of the file, which I works. I tried foreach loops with assigning a variable to $_POST[$key], I tried sending just the string with html hoping that would work. I believe the problem lies in the HTML, or in the AJAX call, because I can make the form submit() to the .php file and then it works, however, that would change the browser location to that file and obviously with AJAX, that's not what I want. Anyone have any ideas (other than JQuery syntax)?
HTML
<form>
<input type="hidden" name="test" id="test" value="testString">
</form>
JavaScript AJAX call
function sendString()
{
var data = document.getElementById("test");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', 'testing.php', true);
xhr.send(data);
}
PHP File
<?php
$line = $_POST['data'];
$file = 'test.txt';
file_put_contents($file,preg_replace('/^.+/',$line,file_get_contents($file),1));
?>
EDIT: Thanks for the responses, but non have worked. I tried:
document.getElementById("test");
document.getElementById("test").value;
and
xhr.send(data.value);
None of these worked. Still Blank lines. I also tried the extended solution.
Your problem is here:
var data = document.getElementById("test");
You're creating a reference to your html element. You need to reference the value property of your element.
var data = document.getElementById("test").value;
Also, you are only sending the value and not a key value pair to the server. So xhr.send(data); will only send the value. Your PHP script won't know that $_POST['data'] is what you mean. You need to format var data as
var data = "data=" + document.getElementById("test").value;
EDIT
To send form data via POST, you may need to add some header information.
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
// change your function
function sendString()
{
var data = "data="+document.getElementById("test").value;
var xhr= new XMLHttpRequest();
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
}
In testing.php you can call them via $_POST:
echo $_POST['data'];
Example here: http://www.openjs.com/scripts/examples/ajax_using_post.php