I have a todo list program and I want it to be reset to a predefined set of json within the json file once a button is clicked. For example, if the json file was full with data and someone clicked the button I want it to edit the json file to just say:
[{"completed":false,"task":"Kitchen - Sweep Floor","important":false}]
This is on cpanel latest using the latest stable php version. I’ve tried fwrite and file_put_contents but can’t seem to get it working.
This is what I’ve tried already:
<html>
<h2>Click</h2>
<form action="" method="post">
<button name="click" class="click">Click me!</button>
</form>
<?php
if(isset($_POST['click']))
{
echo file_put_contents("test.json","[{"completed":false,"task":"Kitchen - Sweep Floor","important":false}]");
}
?>
</html>
When clicking the button nothing happens, no errors or anything?
2
Answers
You haven’t assigned an action to the form, for this to work you should add the URL of the current page (so it redirects to itsself). Only then the post request is sent.
PHP won’t run anything asynchronous: stuff only happens on page load.
You have syntax errors in your script – you have to escape the quotes in the string. Always look at the webserver error log or enable error display during development.
Here is the fixed code:
You should use something like json_decode. Don’t build json by hand: