Skip to content
Advertisement

How can I put input value to the JSON in node.js file

I was making the TODO list web application.

This is the ‘todo.html’ code below :

<html>
<head>
  <title>My TODO List</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="main.css">
  <script>

    $(document).ready(function() {

      $("#submit").click(function() {
        var bla = $('#item').val();
        $("#todo").append("<li class='todoVal'>" + bla + "</li>");
      });

      // $(document).click(function(e) {
      //   if (e.target.className == 'todoVal') {
      //     var t = e.target.innerText
      //     $(e.target).remove();
      //     $("#completed").append("<li class='completedVal'>" + t + "</li>");
      //   }
      // });

      $(document).click(function(e) {
        if (e.target.className == 'completedVal') {
          $(e.target).remove();
        }
      });

      jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
        return this.each(function() {
          var clicks = 0,
            self = this;
          jQuery(this).click(function(event) {
            clicks++;
            if (clicks == 1) {
              setTimeout(function() {
                if (clicks == 1) {
                  single_click_callback.call(self, event);
                } else {
                  double_click_callback.call(self, event);
                }
                clicks = 0;
              }, timeout || 500);
            }
          });
        });
      }
      $(document).single_double_click(function(e) {
        if (e.target.className == 'todoVal') {
          var t = e.target.innerText
          $(e.target).remove();
          $("#completed").append("<li class='completedVal'>" + t + "</li>");
        }
      }, function(e) {
        if (e.target.className == 'todoVal') {
          $(e.target).remove();
        }
      });

      $("#clear").click(function() {
        $("li").remove();
      });

    });
  </script>
</head>

<body>
  <div id="addItem" class="box">
    Task:
    <input id="item" type="text" name="add_item" />
    <button id="submit" type="button">Add</button>
    <button id="clear" type="button">Clear All</button>
  </div>
  <div id="todo" class="box">
    <h4>TODO:</h4>
    <ul></ul>
  </div>
  <div id="completed" class="box">
    <h4>Completed:</h4>
    <ul></ul>
  </div>
</body>

</html>

And this is the ‘app.js’ file below :

var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require("body-parser");

// middleware
app.use(cors());
app.use(bodyParser.json());

var tasks = [];

// This will serve the HTML page todo.html
app.get('/', function(req, res) {
  res.sendFile('todo.html', {
    root: __dirname
  });
});

// GET all tasks
app.get('/tasks', function(req, res) {
  res.set('Content-Type', 'application/json')
  res.status(200).send(tasks);
});

// POST to add a task
app.post('/task', function(req, res) {
  res.set('Content-Type', 'application/json')

  /* HELP ME HERE */

  // returns 201 on success
  res.status(201);
});

// DELETE a task
app.delete('/task', function(req, res) {

  /* HELP ME HERE */

  // returns 204 on success
  res.status(204);
});

// DELETE all tasks
app.delete('/tasks', function(req, res) {

  /* HELP ME HERE */

  // returns 204 on success
  res.status(204);
});

//

// Listen for HTTP requests on port 3000
app.listen(3000, function() {
  console.log("listening on port 3000");
});

I want to pass the text box value to the JSON filter by ‘TODO’ and ‘COMPLETED’.
If I add a new TODO list, it goes to the JSON and if the value goes to COMPLETED, it also goes to the JSON

This is the sample JSON result I want:

{"TODO" : [ "Go to market", "Eat dinner with Daniel"], "COMPLETED" : [ "Wash dishes", "Go to gym and Workout" ]}


This is just an example so you guys can just change the format.
Feel free to give me feedback from everything it’s always welcome. btw I just started studying how to code
Thank you for spending time on this even if you didn’t help me and have a great day!

Advertisement

Answer

What you have to do is simply make an Ajax Call to Nodejs APIs. For example,to '/task' and pass the input field value as params in json format then simply fetch them on in Nodejs as req.params.yourjsonKeys.

var inputData = $("#items").val();

$.ajax({
  url: "/tasks",
  type: "POST",
  data: {params: inputData},
  dataType: "html",
  success: function(data){
     if(data.code === 200){ // the response key 'code' from Nodejs
        alert('Success');
     }
  }
});

Next, once you have the params, all you have to do is write it into your file using file system like so:

Create a javascript object with the table array in it

var obj = {
   table: []
};

Add some data to it like

obj.table.push({id: req.params.id , square: req.params.square});

Convert it from an object to string with stringify

var json = JSON.stringify(obj);
//use fs to write the file to disk

var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);

if you want to append it read the json file and convert it back to an object

fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
    if (err){
        console.log(err);
    } else {
    obj = JSON.parse(data); //now it an object
    obj.table.push({id: 2, square:3}); //add some data
    json = JSON.stringify(obj); //convert it back to json
    fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
}});

Complete Code:

// POST to add a task
app.post('/task', function(req, res) {
  res.set('Content-Type', 'application/json')
    var obj = {
       table: []
    };

    obj.table.push({id: req.params.id , square: req.params.square});
    
    var json = JSON.stringify(obj);

    var fs = require('fs');

    fs.writeFile('myjsonfile.json', json, 'utf8', callback)

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {

        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 

        // returns 201 on success
        res.json({
           code: 201,
           message: 'Success'
        });

    }});

});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement