I have three files 1)index.html 2)data.json 3)app.js loaded on WAMP server I wanted to add data from my JSON file into a table on the HTML file which I was able to do. The functionality I also need is to update the JSON file as i update the HTML table(using ADD, SAVE and DELETE buttons) and save this table data to the external JSON file.
Here are my code snippets: 1) data.json:
{"user":[{"goal":"HTML essential training","type":"Beginner", "date":"20/07/2016"},{"goal":"CSS essential training","type":"Beginner", "date":"30/07/2016"},{"goal":"CSS core concepts","type":"Intermediate", "date":"10/08/2016"},{"goal":"Javascript essential training","type":"Beginner", "date":"20/08/2016"},{"goal":"Object Oriented JS","type":"Advanced", "date":"30/08/2016"}]}
2) app.js
var request= new XMLHttpRequest();
request.open('GET', 'data.json');
request.onreadystatechange=function(){
if((request.readyState===4)&&(request.status===200)){
items=JSON.parse(request.responseText);
console.log(items);
for(var key in items){if (items.hasOwnProperty(key)) {
for (var i in items[key]) {if (items[key].hasOwnProperty(i)){
console.log(items[key][i]);
var output="<tr><td><input type='checkbox' name='record'></td><td>" + items[key][i].goal + "</td><td>" + items[key][i].type + "</td><td>" + items[key][i].date + "</td></tr>";
console.log(output);
$("table tbody").append(output);
output='';
}}
}}
}
}
request.send(); $('.save_button').click( function() {
var table = $('#goal_table').tableToJSON({ignoreColumns:[0]});
// Convert the table into a javascript object
console.log(table);
alert(JSON.stringify(table));
for(var key in items){if (items.hasOwnProperty(key)) {
for (var i in items[key]) {if (items[key].hasOwnProperty(i)){
console.log(items[key][i]);
delete items[key][i];
}}
}}
console.log("items after deleting");
items[key].length=0;
console.log(items[key]);
for(var key in table){if (table.hasOwnProperty(key)) {
for (var i in table[key]) {if (table[key].hasOwnProperty(i)){
console.log(table[key][i]);
items.push(table[key][i]);
}}
}}
});
I don't understand how to accomplish this and seem to have encountered a road block. I'm a beginner to JS and JSON and the above code snippets were what i could manage. Please help!