MrGoofus
MrGoofus

Reputation: 883

Update .json file with jquery post to php file

I'm really new to PHP programming and I'm trying to achieve following structure with PHP to .json file;

{

  "1": {
    "number": "4",
    "color": "black"
  },
  "2": {
    "number": "0",
    "color": "green"
  }

}

What I would like to do is, when I post data to this with "add.php" file. It would update the .json file as below;

{

  "1": {
    "number": "4",
    "color": "black"
  },
  "2": {
    "number": "0",
    "color": "green"
  },
  "3": {
    "number": "12",
    "color": "red"
  }


}

The "number" and "color" would come from the post I post from the index.php with jQuery;

$('#add_outcome').on('submit',function (e) {    
    e.preventDefault();

    $.ajax({
        url: 'add.php',
        cache: false,
        type: 'POST',
        data : {
            "number" : $('#add_outcome select').val(),
            "color" : $('#add_outcome #color_info').val()
        },
        success: function(json) {
            console.log("Done, data sent");             }
    });
});

Is it possible to update this kinda structure with PHP? If it's not possible to count the next "ID" which in my examples are 1, 2, 3 etc (Increasing by submit) I can post the data from index PHP.

Most important to me right now is to get familiar how to update this sort of structure with PHP.

The JSON data would come from file, path to it is "json/outcome.json" .

Upvotes: 2

Views: 1064

Answers (2)

i'm PosSible
i'm PosSible

Reputation: 1393

Add this code into your add.php file

<?php
$json_array = json_decode(file_get_contents('json/outcome.json'), true);

$json_array[] = array('number' => $_POST['number'], 'color' => $_POST['color']);
file_put_contents('json/outcome.json', json_encode($json_array));
?>

Upvotes: 1

mark.sagikazar
mark.sagikazar

Reputation: 1042

Try this code

<?php
$file = json_decode(file_get_contents('path/to.json'), true);
//do whatever you want as $file is now an array
$file[] = array('number' => 12, 'color' => 'red');
file_put_contents('path/to.json', json_encode($file));

Upvotes: 0

Related Questions