Change JSON file on the server

2

I have the following form:

 <form method="POST">
   Title <input type="text" onchange="Function()">
   X <input type="text" onchange="Function()">
   Y <input type="text" onchange="Function()">

  /* others fields */

</form>

and the test.json file

{
    "test":[    
        {
            "title" : "",
            "x" : "",
            "y" : ""        
        }   
    ]
}

How do I get a onchange action on the inputs and the test.json file to be changed and saved automatically on the server?

I'm using PHP, so I'll put the contents of the JSON file into an array:

$jsondados = file_get_contents("test.json");
$json = json_decode($jsondados,true);

Then I can access the array and put it in the variables I want.

I would like suggestions / indications of functions or how to get what is typed in the form to be automatically passed to php variables.

    
asked by anonymous 05.12.2015 / 00:39

1 answer

1

Before reading the file you have to receive the form data in a array of PHP.

$dados_do_formulario = array();

$dados_do_formulario = filter_input(INPUT_POST, 'nome_do_formulario'); /*eu uso esse modo que é igual ao $_POST mesmo, porque dá pra filtrar a variável depois se quiser*/

Second of all, you have to open the JSON file and then decode it as you are already doing.

/* pego o arquivo JSON */

$arquivo_json = file_get_contents("test.json");

/* "transformo" temporariamente ele num array() que o PHP entenda*/
$decodifica_json = json_decode($arquivo_json);

Next, you can use array_push() fault PHP to include the form data in the JSON array (I'm using a simple inclusion as an example, but before adding it, you can grab an existing index and change it or create a function to access the index and delete it, for example).

/* agora, usando o array_push() do PHP, você pode incluir dentro do arquivo JSON (que agora é o array() $decodifica_json) os dados do POST*/

array_push($decodifica_json, $dados_do_formulario);

Then you have to code the JSON again, when everything is done and then save the file, using file_put_content() or a sequence with fwrite() and fclose() .

/* aqui codifico o array() do PHP em um formato JSON novamente */
$arquivo_json_alterado = json_encode($decodifica_json);

/* aqui eu salvo o arquivo laterado JSON*/
file_put_contents('test.json', $arquivo_json_alterado);
    
05.12.2015 / 01:40