I am trying to update the value. Whenever I enter the value, it shows the old value. But when I refresh, it updates to the new value.
P.S. The value is always a number. I don’t mid if there is a better solution to store the number without using databases.
Program Logic: Press set button, update the txt file with the value.
To achieve: It should refresh the value on form submission.
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method="post" action="">
<input type="number" class="" name="data" id="data" min="0" max="200" value="<?php echo file_get_contents('test.txt');?>">
lb
<input type="submit" name="button1" onclick="data_update();" value="Set">
</form>
<br>
<?php
echo("The current value of the data is ");
echo file_get_contents('test.txt');
?>
<script language="javascript" type="text/javascript">
function data_update(){
<?php file_put_contents('test.txt', $_POST["data"]);?>
}
</script>
</body>
</html>
Here’s my test.txt file data:
20
>Solution :
Unfortunately, PHP and JavaScript do not commingle like this. You cannot logically control the execution of PHP code with JavaScript, as PHP is executed on the server, whereas JavaScript is executed on the client.
However, in this context, there is zero need for JavaScript – simply check for the presence of your expected POST parameter at the top of your script and act accordingly:
<?php
if (isset($_POST['data'])) file_put_contents('test.txt', $_POST['data']);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method="post">
<input type="number" class="" name="data" id="data" min="0" max="200" value="<?php echo file_get_contents('test.txt');?>">
lb
<input type="submit" name="button1" value="Set">
</form>
<br>
<?php
echo("The current value of the data is ");
echo file_get_contents('test.txt');
?>
</body>
</html>
I’ve also put together a Repl.it illustrating that this works as you seem to intend.