Reputation: 105
In my code i've a file called "orca.txt" it is just a number writen in this. it looks like:
2300
I use fetch to read this number, i get it with:
fetch('orca.txt')
.then(response => response.text())
.then(textString => { contador=textString; });
It works very well, but then after i need to increase the value from the var contador, so I use contador++; after i wanna to save this new value into the file "orca.txt"
i've tried this:
contador++;
var ct=contador.toString();
fetch("orca.txt",{method:'POST', body:ct})
.then (response => response.text());
but when i refresh the page or open in server the file orca.txt the value is same.
Can anyone help me how to write a value into a file (server file, no user file) using POST method?
Upvotes: 1
Views: 2179
Reputation: 206477
Using PHP and file_put_contents and JS's Fetch API with FormData API
Create an index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DEMO</title>
</head>
<body>
<button id="increment" type="button">INCREMENT</button>
<input id="counter" type="text" readonly>
<script>
const EL_increment = document.querySelector("#increment");
const EL_counter = document.querySelector("#counter");
let counter = 0;
const incrementCounter = () => {
counter = parseInt(counter) + 1;
const FD = new FormData();
FD.append("counter", counter);
fetch("saveCounter.php", {
method: 'post',
body: FD
}).then(data => data.json()).then((res) => {
EL_counter.value = res.counter;
});
};
const init = async () => {
EL_increment.addEventListener("click", incrementCounter);
counter = await fetch('counter.txt').then(response => response.text());
EL_counter.value = counter;
};
init();
</script>
</body>
</html>
create counter.txt
file:
2300
Create a saveCounter.php
file:
<?php
$response = ["status" => "error"];
if (isset($_POST["counter"]) && file_put_contents("counter.txt", $_POST["counter"])) {
$response = ["status" => "success", "counter" => $_POST["counter"]];
}
echo json_encode($response);
exit;
Spin up your localhost server or for a quick test using cli-server
run from terminal:
php -S localhost:8081
and head to http://localhost:8081 to try it out
Upvotes: 3