0

I'm currently using Node.js to serve a webpage that takes in user inputs which are stored on a mongodb server. The web page also displays specified or all user inputs entered. I'm trying to figure how to pass the user inputs from node.js to the <p> element.

In my node.js file I am responding with the user data as a string like so:

response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stringifyMongoDBCollection(user_data_collection));
response.end();

When I do this, this re-directs the client to display the content as text/plain which I expected. The next step is to update just the content of <p>. How can I do this? I thought about re-serving the entire html content with the new populated <p> but that would make all current user inputs disappear...

The user data would be a mongodb collection array and look like this:

 [ { _id: 5dda17065f7e9b64282e7291,
    date: 'Sat Nov 23 2019 21:37:10 GMT-0800 (Pacific Standard Time)',
    field: '127' },
  { _id: 5dda18ecf330d521a035c444,
    date: 'Sat Nov 23 2019 21:45:16 GMT-0800 (Pacific Standard Time)',
    field: 125},
  { _id: 5dda1951f330d521a035c445,
    date: 'Sat Nov 23 2019 21:46:57 GMT-0800 (Pacific Standard Time)',
    field: '111' } ]
tyleax
  • 1,556
  • 2
  • 17
  • 45

1 Answers1

2

You could do something like this.

In Node section

res.status(200).send(stringifyMongoDBCollection(user_data_collection));

Client side

function getContent() {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/todos",
    success: function (res) {
      if (res) {
        res = res.slice(0, 5); // limiting data to 5
        var val = '';
        res.forEach(todo => {
          val += '<p><b>Title:</b>' + todo.title + '  <b>Completed:</b> ' + todo.completed + '</p>';
        });
      }
      $("#content").html(val);
    },
    error: function () {
      var val = '<p>Error in loading content</p>'
      $("#content").html(val);
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="getContent()">Get Content</button>

<h1>Todo</h1>
<div id="content"></div>

References

jQuery ajax() Method

Node.js - Response Object

AJAX Introduction

hbamithkumara
  • 2,344
  • 1
  • 17
  • 17
  • Thanks for that, that did the trick. I did have to make some small changes. I didn't use `res.status(200)...` since that is node.js express syntax. I ended up using `response.writeHead(200, {"Content-Type": "text/plain"}); response.write(stringifyMongoDBCollection(user_data_collection)); response.end();`. Also inside `function(res)` on the client side, I had `$("#content").html(res);` – tyleax Nov 26 '19 at 05:11
  • 1
    Cool. The example was just to give an idea. – hbamithkumara Nov 26 '19 at 05:17