I stuck at the JSON file whereby the value is not updated.
Reference:
- How to update/edit a JSON file using PHP [closed]
- Add, Update, Delete and Read JSON Data/File in PHP
- Modifying a JSON file with PHP
JSON (../assets/data/maintenance.json)
[
{
"maintenance_status":"off"
}
]
PHP (file_update.php)
<?php
$data = file_get_contents('../assets/data/maintenance.json'); // able to read file
$json_arr = json_decode($data, true);
$newValue = $_POST['newValue'];
foreach ($json_arr as $key => $value) {
$json_arr[$key]['maintenance_status'] = $newValue;
}
file_put_contents('../assets/data/maintenance.json', json_encode($json_arr));
echo json_encode($json_arr); // return [{"maintenance_status":"on"}] at jQuery success response
?>
jQuery
$('.maintenance-toggle').on('click', function(){
$('.maintenance-toggle').toggleClass('on');
if ($('.maintenance-toggle').hasClass('on')){
updateValue("on");
}
else if ($('.maintenance-toggle').hasClass('off')){
updateValue("off");
}
});
function updateValue(newValue) {
console.log(newValue); // received "on" or "off"
$.ajax({
url : '../src/files/file_update.php',
type : 'POST',
data: {
newValue: newValue
},
cache: false,
success: function(response){
console.log(response); // success since received result from echo php but not update the value in JSON
},
error: function(e){
}
});
}