使用JavaScript将从API检索的数据写入主机服务器

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, "
");
    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 . "
" . $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.