I have a polymer package structure from the app-drawer-template, with a folder named src. In this folder I have a file called entries.json. I am trying to figure out how to add items to this json object when a user submits form data from a paper-dialog. I understand how to get the values from this form. I can't seem to figure out how to get the contents from the json file and add a new item to this json and then write the new item back to the .json file.
here is my form:
<paper-dialog id="applynow" entry-animation="scale-up-animation" exit-animation="fade-out-animation">
<paper-dialog-scrollable>
<img src="/images/logo.png" width="80%" height="auto" style="margin: 0 auto;"/>
<paper-input id="name" label="Full Name"></paper-input>
<paper-input id="phone" label="Phone Number"></paper-input>
<paper-input id="email" label="Email"></paper-input>
<paper-textarea id="desc" label="Why Pick You?" char-counter maxlength="400"></paper-textarea>
<paper-button on-click="submitForm">Submit</paper-button>
</paper-dialog-scrollable>
</paper-dialog>
And here is the javascript:
submitForm: function() {
var data = JSON.parse("/src/entries.json");
data.entries.push({
name: this.$.name.value,
phone: this.$.phone.value,
email: this.$.email.value,
desc: this.$.desc.value
});
data = JSON.stringify(data);
}
I have been trying but I see from the chrome console that when I use JSON.parse() it is expecting the input to be a json formated string of text, not a filepath. Is there a way to read from this file and then write back to it in javascript? This file is not stored on the user's storage but just in my package structure.
EDIT:
Thanks to chrisv I was able to read and append to my json but I still need a way to rewrite this json file. Here is my new javascript function that will successfully grab my json file add a new entry and then display it in the console. Is there an easy way to rewrite this .json file with the new line?
submitForm: function() {
var newName = this.$.name.value;
var newPhone = this.$.phone.value;
var newEmail = this.$.email.value;
var newDesc = this.$.desc.value;
var json = $.getJSON("src/entries.json", function(data) {
data.entries.push({
name: newName,
phone: newPhone,
email: newEmail,
desc: newDesc
});
console.log(data);
});
}