I was trying to find anwser but maybe I'm not using the right terms for my problem so I need to ask here:
I made a webapp that loads a larger array of objects from a JSON file. If necessary the user will update some part of the array, delete objects or can push new data.
Because of this when the user decides to save the array back to JSON file with JQUERY AJAX, in my PHP that handles the data I use 'w+' tag so I delete the content and write back the whole new and modified content.
The issue is that even if the JSON file is used by a single user sometimes the writing process breaks before the whole content would be writen to that cleared file. This couses important data loss.
// I do make security savings to backup files, but this means every time the saving breaks I have to copy the last backup JSON file over the original JSON file from where the webapp loads data and until I do that nobody can use my webapp.
This is my JQUERY AJAX in a .js file:
$.ajax
({
url: 'json/save_json.php',
type: 'POST',
dataType : 'json',
data: { pid: currentdate, data: JSON.stringify(allinfobj), userlevel: jslevel},
complete: function(){alert("this worked out!")};
});
My save_json.php:
<?php
$datecode = $_POST['pid'];
$myFile = "work".$datecode.".json";
$userData = $_POST['userlevel'];
if($userData != 4 && $userData != 3){
$fh = fopen($myFile, 'w+') or die("Error while opening the file.");
flock($fh, LOCK_EX); // acquire an exclusive lock
$stringData = $_POST['data'];
fwrite($fh, $stringData);
flock($fh, LOCK_UN);
fclose($fh);
}
?>
I use certain variables there like $userData or $datecode. Those have nothing to do with the fact that fwrite breaks. Hope it's not confusing anyone, I assure you those work well.
The resulting JSON file normally is something like:
[{"name":"Apple","color":"red","quality";"awful"};{"name":"Tesla","color":"metallic","quality";"improved"};{"name":"Shoe","color":"white","quality";"fake"};{"name":"Glass","color":"undefined","quality";"good"};{"name":"Jessica","color":"private","quality";"private"}]
But sometimes my result because of a break that I don't understand is this:
[{"name":"Apple","color":"red","quality";"awful"};{"name":"Tesla","color":"met
So next time the user can't load this JSON data beacuase it's missing content and it's not ever a correct array or JSON.
a
pr a+
in PHP I think is not a solution because I often need to replace or delete older JSON objects in the array so I can't get away by appending to the existing data, or the new array might be shorter then the old one.
FYI: in my ajax call success
and error
tags won't do anything. I don't know why. complete
works though, as you can see, I use it in my code.
I hope I made my self fairly clear and I will be very grateful for any suggestions that why writing to a JSON file breaks. Where should I look to understand and fix this. Thanky you!