Raja G
Raja G

Reputation: 6653

How to update JSON file using HTML forms and Javascript?

I am trying to update a JSON file with structure as below

[
      {
         "fname" : "August",
         "lname" : "somename",
      }
]

I am using HTML & Javascript to handle the operation. I somehow managed to get to updating this existing object with new form data but not sure how to push this updated object to file. I searched in the internet but found answers in PHP, I am trying to achieve this using Javascript.

Any suggestions greatly appreicated.

<div class="col-lg-4 col-md-4 col-sm-4">
                <form id="forddata">
                    <input id="fname" name="fname" type="text" placeholder="Enter your firstName" />
                    <input id="lname" name="lname" type="text" placeholder="Enter your lastnane" />
                    <input type="button" id="bt" value="save-to-file" onclick="saveFile()" />
                </form>
            </div>
            <script>
                function saveFile() {
                    var fname = document.getElementById( 'fname' );
                    var lname = document.getElementById( 'lname' );

                    var data = 'First Name: ' + fname.value + ',\n'
                        + 'Last Name: ' + lname.value + ',\n';
                    console.log( data );
                    console.log( "Current formata : " + JSON.stringify( formdata ) );
                    formdata.push( { "Firstname ": fname.value, "Lastname": lname.value } );
                    console.log( typeof formdata );
                    console.log( JSON.stringify( formdata ) );
                    // How to push updated object "formdata" back to file ?
            </script> 

Upvotes: 0

Views: 1094

Answers (1)

Meatgear
Meatgear

Reputation: 139

It is not exactly clear what you are trying to do. But there is the FileSystem API which could help with your issue. But please consider the following:

  1. If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
  2. If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
  3. To store some information on the client side that is considerably small, you can go for cookies.
  4. Using the HTML5 API for Local Storage.

Upvotes: 2

Related Questions