Home > Back-end >  How to send data from NodeJS server side to the JS client side, only when data is ready?
How to send data from NodeJS server side to the JS client side, only when data is ready?

Time:07-19

On my website, when the user clicks on a button, some user's data will be stored in a database and after that I want the server to send notification data to the Javascript frontend file to change the UI.

Right now, the Js file (index.js) receives data right after the website loads (always false). I want it to be received only when the data is ready on the server.

I searched a lot but couldn't find an answer to my problem?

I appreciate any help :)

server.js

var requestValidation = false;

app.post("/", function(req, res){

  var name = req.body.personName;
  var email = req.body.personEmail;
  var collabTopic = req.body.collabTopic;

  const newUser = new User({  //mongoDB schema
    name: name,
    email: email,
    collabTopic: collabTopic
  });

  newUser.save(function(err){ //adding data to mongoDB
    if(!err){
      requestValidation = true;
    }
  });

});

app.get("/succ", function(req, res){
  res.json(requestValidation);
});

index.js

const url = "http://localhost:3000/succ";
const getData = async (url) => {
  try {
    const response = await fetch(url);
    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.log(error);
  }
};

getData(url);

CodePudding user response:

I'm not sure this is completely the answer you're looking for, but it's definitely a tool/feature to consider as you rework your approach.

app.post("/", async (req, res) => {
    let result = await INSERT MONGODB UPDATE OR INSERT FUNCTION;
    res.render("YOUR TEMPLATE", result);
});

You probably can't plug and play this, but when you finish a MongoDB operation, it returns a json object with some details on whether or not there was success. For example, a MongoDB insert operation returns something like this (stored in the variable result that I created)

{ "acknowledged" : true, "insertedId" : ObjectId("5fd989674e6b9ceb8665c57d") }

and then you can pass this value on as you wish.

Edit: This is what tkausl referred to in a comment.

CodePudding user response:

Here is an example if you want to pass the content of a txt file to the client with express and jquery: in express:

app.get('/get', (req, res) => {
    fs.readFile('test.txt', (err, data) => {
        if (err) throw err;
        return res.json(JSON.parse(data));
        })
    })

jquery in client side:

$.getJSON( "http://localhost:3000/get", function( data ) {
geojsondata1 = JSON.stringify(data)
}

now you can do anything you want with the variable data

  • Related