What I'm trying to do is to create a json file with a form, and then with a second form, update the json file that was created. All of this currently takes place in process.php
. I'm having success with the second form if I name the json file as data.json
first in process.php
(now commented out), but I'm wanting to be able to create that name instead from an input from the first form. Can anyone see what I'm doing wrong? Nothing happens upon submitting the first form. No json file is created.
First form:
<form class="ui equal width form" action="server/php/process.php" method="POST" target="frame">
<input type="text" name="filename" id="filename">
<input type="submit" value="Save and continue" id="continue1">
</form>
Second form:
<form class="ui form" action="server/php/process.php" method="POST" target="frame" id="attribute-form">
<input type="text" value="" class="ID" name="ID">
<input type="hidden" value="" class="value-x" name="valueX">
<input type="submit" value="Save" id="save-snippet">
</form>
process.php
<?php
// Form for saving template file name
$myFile = $_POST['filename'];
if(isset($_POST['filename'])){
$handle = fopen("server/php/data/$myFile.json", "w+");
fwrite($handle);
fclose($handle);
} else {
echo 'Template has not been named. Please enter a name before saving.';
}
// Form for saving attribute JSON data
//$myFile = "data/data.json";
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'ID'=> $_POST['ID'],
'valueX'=> $_POST['valueX'],
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
$updateKey = null;
foreach ($arr_data as $k => $v) {
if ($v['ID'] == $formdata['ID']) {
$updateKey = $k;
}
}
if ($updateKey === null) {
array_push($arr_data,$formdata);
} else {
$arr_data[$updateKey] = $formdata;
}
//Convert updated array to JSON
$jsondata = json_encode($arr_data);
//write json data into json file
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>