skip to Main Content

I am trying to send data from my nodejs server with ejs to my html. But the problem is I cant read the variable inside my script.

Nodejs server:

exports.getIndex = (req, res, next) => {
  var alert = req.query.msg;

  // connect to your database
  mssql.connect(config, function (err) {
    if (err) console.log(err);
    var request = new mssql.Request();

    request.query(
      "SELECT startDate, endDate  from Reservations",
      function (err, recordset) {
        if (err) console.log(err);
        events = [];
        recordset.recordset.forEach((element) => {
          reserv = {};
          reserv.start = element.startDate;
          reserv.end = element.endDate;
          events.push(reserv);
        });
        res.render("index", {
          alert: alert,
          events: events,
        });
      }
    );
  });
};

I need to read events inside my html with smth like this:
var events = <%= events %>

but I get console error that events doesn’t exist. Any idea how can I fix this or how can I make it work different way?

I tried creating div and direct assigning but it didn’t worked.

2

Answers


  1. Chosen as BEST ANSWER

    Just to update this issue, I found solution that works for me.

                    <script> var eventsC = []; </script>
    
                <% events.forEach((element) => {%>
                <script>
                    reserv = {};
                    reserv.start = "<%= element.start %>";
                    reserv.end = "<%= element.end %>";
                    eventsC.push(reserv)                    
                </script>
                  <% }); %>
    

  2. You seem to be passing events correctly to your ejs views by using res.render so if you are confident that events is populated and that you don’t have any database errors then the objects in your events array can be accessed like so:

    <ul>
      <% events.forEach(function(event) { %>
        <li>
          Start: <%= event.start %> | End: <%= event.end %>
        </li>
      <% }); %>
    </ul>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search