Append to JSON file from form entry

I have a .json file stored on my server in www/ajax/data.json with the following contents:

data.json

{
  "Endorsements": [{
    "Name": "Bob",
    "Date": "01/02/2017",
    "Message": "How's it going?"
  }, {
    "Name": "Sally",
    "Date": "01/01/2017",
    "Message": "Konichiwa"
  }, {
    "Name": "Sue",
    "Date": "01/10/2017",
    "Message": "Peace be unto you"
  }, {
    "Name": "Roger",
    "Date": "02/12/2017",
    "Message": "Namaste"
  }, {
    "Name": "Zed",
    "Date": "09/12/2017",
    "Message": "sup"
  }, {
    "Name": "Quail",
    "Date": "10/12/2017",
    "Message": "Chirp"
  }]
}

The data.json contents are successfully displayed and refreshed every 5 seconds on my messages.php page through an ajax function in messages.js.

On messages.php I have a <form> where users can leave a new message. The typed entries in the Name, Date, and Message fields are stored in localStorage through functions in messages.js.

How can I retrieve the localStorage data and use it to append a new message entry onto my data.json file?

Answers 1

  • I hope this code can help you, its just a function used to add an object to an existing json variable.

    var json = JSON.stringify({
      "Endorsements": [{
        "Name": "Bob",
        "Date": "01/02/2017",
        "Message": "How's it going?"
      }, {
        "Name": "Sally",
        "Date": "01/01/2017",
        "Message": "Konichiwa"
      }, {
        "Name": "Sue",
        "Date": "01/10/2017",
        "Message": "Peace be unto you"
      }, {
        "Name": "Roger",
        "Date": "02/12/2017",
        "Message": "Namaste"
      }, {
        "Name": "Zed",
        "Date": "09/12/2017",
        "Message": "sup"
      }, {
        "Name": "Quail",
        "Date": "10/12/2017",
        "Message": "Chirp"
      }]
    });
    
    localStorage.setItem("newObject", JSON.stringify({
    	"Name": "test",
      "Date": "01/02/2017",
      "Message": "This is a test"
    }));
    
    function addToJsonFile(){
    	if(localStorage.getItem("newObject") !== undefined && localStorage.getItem("newObject") !== ""){
      	var jsonObjects = JSON.parse(json);
        jsonObjects.Endorsements[jsonObjects.Endorsements.length] = JSON.parse(localStorage.getItem("newObject"));
        json = JSON.stringify(jsonObjects)
      }
    }


Related Articles