11

I'm trying to update individually loaded .json files according to whichever option in the <select> is chosen. It loads the .json file and then updates an individual file fine as long as I define $myFile as a specific .json file such as $myFile = "data/data.json";

But when I attempt to pass the select option as the filename, nothing saves. Where am I messing this up?

Here is the HTML select:

<form action="/server/php/data/process.php" method="post">
    <select class="ui mini fluid search dropdown" id="templateSelection" type="text" name="selectTemplate" onchange="loadTemplate()">
        <option value="" selected="selected">Select Template</option>
        <?php
            foreach(glob(dirname(__FILE__) . '/server/php/data/*') as $filename){
                $filename = basename($filename);
                echo "<option value='" . $filename . "'>".$filename."</option>";
            }
        ?>
   </select>
</form>

Here are the options that get populated:

<option value="data.json">data.json</option>
<option value="data2.json">data2.json</option>
<option value="data3.json">data3.json</option>

And here is process.php:

<?php

//$myFile = "data/data.json";
$filename = $_POST['selectTemplate'];
$myFile = "data/" . $filename;
$arr_data = array(); // create empty array
try
{
    //Get form data
    $formdata = array(
        'ID'=> $_POST['ID'],
        'attributeName'=> $_POST['attributeName'],
        '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;
    }

    $jsondata = json_encode($arr_data);

    //write json data into data.json file
    if(file_put_contents($myFile, $jsondata)) {
        echo 'Data successfully saved';
    }
    else
        echo "error";
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
?>

EDIT: I'm submitting it (with a submit button) via another form on the same page with the same action. This other form allows me to change some of the values of the json that is loaded when an option in the first form is selected. Here is what this second form looks like:

<form class="ui form" action="server/php/process.php" method="POST" target="frame"> .... <input type="submit" value="Save"> </form>

Perhaps that is where the issue is coming from? I figured a submit on this 2nd form would pick up the selected option in the first form and store the option in a variable.

Todd Williams
  • 267
  • 2
  • 16
  • 1
    I think the reason why you cannot modify data is the wrong path to file that is being saved. I assume that the php script cannot even read json content by the path from `$myFile`, can it? Additionally please check file permissions for write access as well. – Andy Dec 29 '17 at 15:19
  • I'll have to test whether it can read data from `$myFile`. I know that I do have write permissions because I can overwrite the `json` file if I uncomment `$myFile = "data/data.json";` – Todd Williams Dec 29 '17 at 15:37
  • The problem comes when I replace `$myFile = "data/data.json";` with `$filename = $_POST['selectTemplate']; $myFile = "data/" . $filename;` – Todd Williams Dec 29 '17 at 15:38
  • So you didn't inspect what exactly you got in your variable and you dont know what is there, right? – Andy Dec 29 '17 at 16:32
  • Sorry for the delay, was moving cross-country. I have the console outputting the variable values now. $filename is outputting as `null`, and $myFile is outputting as `data/`. So it seems like `$filename = $_POST['selectTemplate'];` is not picking up the value from the ` – Todd Williams Jan 11 '18 at 15:21
  • How do you post to process.php? Submit button or javascript? – Jannes Botis Jan 11 '18 at 16:40
  • submit button.. – Todd Williams Jan 11 '18 at 16:46
  • 2
    You should check what gets posted with your browser's dev tools. – Mathieu de Lorimier Jan 11 '18 at 18:09
  • So basically your question has nothing to do with JSON but rather with $_POST not being populated. You should check: https://stackoverflow.com/questions/1282909/php-post-array-empty-upon-form-submission and see if an answer helps. – rlanvin Jan 11 '18 at 19:22
  • 2
    If you're submitting by sumit button, what does the onchange="loadTemplate()" do? Any chance it messes up with select option values? – Sergey Benzenko Jan 12 '18 at 07:24
  • I updated the question with some relevant information that will hopefully help. – Todd Williams Jan 12 '18 at 13:48
  • I figured out the problem. I thought magically I could pick up the ` – Todd Williams Jan 12 '18 at 14:23
  • check for the name of select element "selectTemplate". might be some spelling issue or something (if there is issue regarding not getting the file name). It will be helpful if you can provide the full html markup for the form. – Tarun Jan 16 '18 at 12:58

4 Answers4

1

Try adding the submit button within the parent form of your select element (and remove the onchange handler for debugging).

As you wrote: "EDIT: I'm submitting it (with a submit button) via another form on the same page".

HTML-forms can not be nested and a submit button submits only the direct parent form (unless you use some javascript magic).

Note: In case you really want to submit the fields of 2 forms, have a look here:

Submit multiple forms with one submit button

michael - mlc
  • 376
  • 5
  • 5
1

When submitting HTML forms, browsers only post fields within the <form></form> tags.

Easy solution is to make all the fields under one form, or you can use Javascript to populate a hidden field on the actual form you are submitting.

Heinrich Lee Yu
  • 1,472
  • 15
  • 31
1

The easiest way to debug it would be this:

var_dump($_POST);
$filename = $_POST['selectTemplate'];
var_dump($filename);
$myFile = "data/" . $filename;
var_dump($myFile);
$arr_data = array(); // create empty array

If it's the case that everything works when you hardcode $myFile = 'data/data.json - most probably one of those vars are not holding what you would expect them to hold.

Greg
  • 5,862
  • 1
  • 25
  • 52
1

I understand, your actual HTML-Code looks something like this:

<form class="ui form" action="server/php/process.php" method="POST" target="frame">

    <form action="server/php/process.php" method="get">
        <select class="ui mini fluid search dropdown" id="templateSelection" type="text" name="selectTemplate" onchange="loadTemplate()">
            <option value="" selected="selected">Select Template</option>
            <option value="data.json">data.json</option>
            <option value="data2.json">data2.json</option>
            <option value="data3.json">data3.json</option>
       </select>
    </form>

<input type="submit" value="Save">
</form>

When you set the method='get' you can probably see, that your submit-button doesn't do anything. And here's why: Nested forms are not allowed in HTML. If you look at something like the Firefox-Inspector, you can how the browser is handling the exact same code:

The same code in Firefox-Inspector

As you can see, the browser removes the start of your inner <form>-tag and the end of your outer <form>-tag. In the result, your submit-button is outside of the form and is therefore useless.

Jere
  • 1,196
  • 1
  • 9
  • 31