Adding new object to Json file with jquery

I have a simple json file with a few data. for example:

{ "id": 1,
    "name": "Porsche",
    "type": "911", 
    "price": "135000", }`         

i have to create a html form with these inputs(name, type,price) and if the user clicks on the submit button, it will add the new object to the json file.

is this possible by only using jquery, js and html?

Upvotes: 0

Views: 67

Answers (1)

moronator
moronator

Reputation: 303

If you host your website with something like apache it's not possible to save data on server-side just with html and js. For this you will need some sort of Back-End logic. This can be done with PHP for example. If you use PHP the following code will kind of do what you want:

<?php


   $myFile = "data.json";
   $arr_data = array(); // create empty array

  try
  {
       //Get form data
       $formdata = array(
          'id'=> $_POST['id'],
          'name'=> $_POST['name'],
          'type'=>$_POST['type'],
          'price'=> $_POST['price']
       );

       //Get data from existing json file
       $jsondata = file_get_contents($myFile);

       // converts json data into array
       $arr_data = json_decode($jsondata, true);

       // Push user data to array
       array_push($arr_data,$formdata);

       //Convert updated array to JSON
       $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

       //write json data into data.json file
       if(file_put_contents($myFile, $jsondata)) {
            echo 'Data successfully saved';
        }
       else 
            echo "error";

   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }

?>

In addition to that you will have to create a html-form:

<html>
   <head>
   </head>
   <body>
      <form action="save.php" method="POST">
         <input type="text" name="name"/>
         <!-- INSERT YOUR HTML-INPUTS HERE -->
      </form>
   </body>
</html>

If you're not familiar with PHP yet, take a look at this: https://www.w3schools.com/php/php_intro.asp

Upvotes: 1

Related Questions