First of all that is what databases are for. but assuming that you still want to write to .txt file,you need to make an ajax request to server with the content and have php write to that text file for you. Below are some sample codes for the same
function post(ans) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
}
};
xhttp.open("GET", "/result.php?answer="+ans, true);
xhttp.send();
}
and the php script for that would be
<?php
$fname = "answer.txt";
$result = $_GET["answer"];
file_put_contents($fname,$result);
?>
assuming that you over-write the file each time, or
<?php
$fname = "answer.txt";
$result = $_GET["answer"];
$prev = file_get_contents($fname);
$result = $result.",".$prev;
file_put_contents($fname,$result);
?>
also you can go fancy and json encode the data, but the right way to go would be to create a database