I'm trying to update json file on the server on button click.
So when i click the button #update
I'm collecting values from input fields and insert them to json object then I sent this json object to controller.php.
But how to handle this json object delete the old json file and and create new json file with the json object in it.
Lets say the json file path is : js/currencies.json
JS:
function ajaxPost(obj){
$.ajax({
type: "POST",
dataType: "json",
url: "controller.php",
data: {myData:obj},
contentType: "application/json; charset=utf-8",
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
}
$(document).ready(function(){
$('#update').on('click', function(){
var objrates =
{
"EURbuy" : $('#eurbuy').val(),
"EURsell" : $('#eursell').val(),
"USDbuy" : $('#usdbuy').val(),
"USDbuy" : $('#usdbuy').val()
}
ajaxPost(objrates);
});
});
PHP :
<?php
$data[] = $_POST['myData'];
$inp = file_get_contents('js/currencies.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('js/currencies.json', $jsonData);
?>
The php code works withouth errors but the .json file is not replaced with the new values