-1

I have a JSON file called jsondb.json, I also have a file called index.html, in the index.html I have a input tag and a button. So I want when ever I write something in the input tag then click the button, the value of the input will be save in my json file.

Index.HTML

<input placeholder='txt' id='txt' />

<button>save</button>

JSON FILE

{"txt":""}

Emem Edem
  • 21
  • 1
  • 5

2 Answers2

0

You need to wrap your input and button in a form tag with and action attribute and a method attribute (assuming you are in php). The action attribute refers to the page processing your results, and the method attribute is the action used to send your form data to the server. In your action page, you need to get the parameters sent from your page with a $_GET[param] or $_POST[param] depending on the value of your method attribute. Then you can write the value in a file with the json_encode function in PHP

For exemple:

index.php (note the .php)

    <form action='somepage.php' method='GET'>
        <input type="text" name="text" placeholder="txt">
        <button type="submit">Save<button>
    </form>

somepage.php

    //get the results
    $txt=$_GET['text']
    $array = ["text"=>$txt]
    
    //write the result in a text file
    $json = json_encode($array)
    $file=fopen('jsondb.json')
    fwrite($file,$json)
    fclose($file)
Fiouze
  • 69
  • 5
-1

Well, this answer requires PHP but assuming you have a web server, this is my answer:

var object = {
  txt : ""
}
function save(){
  var txt = $("#txt").text();
  object.txt = txt;
  savetofile(JSON.stringify(object));
}
function savetofile(txt){
         $.ajax({
               type: "POST",
               url: "process.php",
               data: {  
                        'file': txt
                 },
            });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder='txt' id='txt' />

<button onClick="save()">save</button>

process.php:

<?php
file_put_contents("jsondb.json", $_POST["file"]);
?>
doo_doo_fart_man
  • 394
  • 3
  • 11