0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much for your answer, me and my cousin trying to create a test website. we discussed, and im gonna create the front end and he will do the back end. and i wasn't sure who has to do this part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.