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.
Related
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.
I'm a php noob forced to add minor functionality to an existing php server. My task is for my php server to return a list of images to the client which will then be displayed on a page.
My JavaScript client code is here:
const http = new XMLHttpRequest();
const url = "http://myaddress.com/myphpserver?";
http.open("GET", url);
http.send();
http.onreadystatechange = (e) => {
console.log(http.responseText);
}
I've tried this code on my server:
$im = imagecreatefrompng("myImage.png");
header('Content-Type: image/png');
imagepng($im);
found here but to no avail
my http.responseText is always empty. Am i going about this the wrong way?
There is no need to send the image as the response from PHP.
What you should do instead instead is return JSON with a URL to the image. Like this:
{
"images": [{
"url": "http://myaddress.com/image_of_cat.jpg"
},
{
"url": "http://myaddress.com/image_of_cat.jpg"
}
]
}
And then with javascript you just set the src attribute of the <img> tag with that URL.
Now you only need to set up a very simple server that serves images from a folder
Does not answer OP's question. Answering for those googlers who actually WANT PHP to send the raw image instead of an image link:
<?php
/* Must be done before headers are sent */
header('Content-Type: image/jpeg');
$path = 'myfolder/myimage.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;
?>
(Partially makes use of another stackoverflow answer on a different question on how to encode image, but if you have the string already encoded from somewhere else, that works as well can replaced the $base64 string )
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
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.
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