TheLuminor
TheLuminor

Reputation: 1411

How to add JSON objects to an array in another JSON file

I have a JSON file as :

var info = [{ "place": "Turkey", "username": "jhon" }, { "place": "Dubai", "username": "bruce" }, { "place": "Italy", "username": "Wayne" }];

I have an HTML form as :

<!DOCTYPE html>
<html>
    <body>

<form onsubmit="addToJSON();">
First name:<br>
<input type="text" id="place">
<br>
Last name:<br>
<input type="text" id="username">
<br><br>
<input type="submit" value="Submit">
</form> 
<script src="data.json"></script>
<script>
function addToJSON(){
    alert("inside JS");
    var x = document.getElementById('place').value;
    var y = document.getElementById('username').value;
    var obj = {
    place: x,
    username: y
};
localStorage.setItem("info",JSON.stringify(obj));
}
</script>

</body>
</html>

I am trying to get the values that the user inputs in the form and add them to the JSON var that I have. But I am going wrong somewhere.Help much appreciated! So that if the user enters wayne and india in the form, my JSON array must have those two objects added to them. Plus they should reflect in the file.

Upvotes: 1

Views: 978

Answers (2)

Quentin
Quentin

Reputation: 944081

It isn't possible to write to arbitrary files or URLs from browser-side JavaScript.

You would need to bundle the data up in an HTTP request (using XMLHttpRequest or just getting rid of the JavaScript and submitting the form normally), send it to an HTTP server, and then have a server side program (written in the programming language of your choice, which could be JavaScript via Node.JS) edit the file.

(Editing files on servers is generally a bad idea and using a database is normally a better option).

Upvotes: 1

Raghavendra
Raghavendra

Reputation: 3580

you can do like this

<!DOCTYPE html>
<html>
    <body>

<form onsubmit="addToJSON();">
First name:<br>
<input type="text" id="place">
<br>
Last name:<br>
<input type="text" id="username">
<br><br>
<input type="submit" value="Submit">
</form> 
<script src="data.json"></script>
<script>
if(!localStorage.getItem('info'))
    localStorage.setItem("info",JSON.stringify(info));
else
    info = JSON.parse(localStorage.getItem("info"));
function addToJSON(){
    alert("inside JS");
    var x = document.getElementById('place').value;
    var y = document.getElementById('username').value;
    var obj = {
    place: x,
    username: y
    };
    info.push(obj);
    localStorage.setItem("info",JSON.stringify(info));
}
</script>

</body>
</html>

Upvotes: 1

Related Questions