0

I have the app.js file on server side and the index.ejs on client side. I need to call a function from the server side on the index.ejs and get a feedback on the index.ejs that the function was executed.

Index.ejs:

function getData(sessionid, numberOrigin){

//console.log(sessionid);
    $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: "application/json",
        url: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx/data/query',
        data: JSON.stringify({  "sessionID": sessionid, 
                                "xxxxxxx":"xxxxxData",  
                                "parameters": { "data": context.data} 
                            }),
        success:function(output) {
            //console.log(output);
            var name = output.result[0].test;
            alert(test);

        },
        error:function(output) {
            return '0';

        console.log(output);
       }
    });
    };

App.js:

 function updateMessage(res, input, response) {

        if (context.counter === 2) {
          getData(); //function inside index.ejs

       // console.log('it's ok');  //it works fine
      }

I'm new to node.js. Hopefully someone can help me on this. If have other alternative or best practices for solved this please let me know.

  • server sends html to client ... that's it ... connection closed, there is no two way communication without using something like AJAX ... and having server initiate a "conversation" with the web page at some arbitrary future point in time is not simple ... you'd need something like Web Sockets, or Server Sent Events – Jaromanda X Feb 01 '17 at 13:02
  • Socket.io is the way which you should choose. – Deep Kakkar Feb 01 '17 at 13:54

1 Answers1

0

If it's necessary to call client side function from server then you will need some kind of open connection like Websockets, and on client side listen for a new message from server and react accordingly.

Some examples can be found here: How can I call a javascript function on client browser from NodeJS server side?

Community
  • 1
  • 1
Christian Safka
  • 317
  • 1
  • 9