Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value from a console.log to html

The function I have written works fine and the value correctly writes to my terminal onSubmit, however I'm struggling to piece together why this code isn't updating my html.

router.post('/index', function(req, res, next) {

  // ...Get form values, do calculations to get toCost value.

      console.log('$' + toCost);

      $(document).ready(function() {
        var output = document.getElementById('cost');
        output.innerHTML = toCost;
      });

  res.location('/');
  res.redirect('/');
})

I receive the following error and jquery is loading fine.

$ is not defined

Admittedly this is an over-engineered node/express app. The code snippet lives wrapped in a route file, inside a post request.

How do I get my value onto the html?

Jade layout

extends layout

block content
  form(...)
  div#cost
like image 801
Rhys Edwards Avatar asked May 28 '26 20:05

Rhys Edwards


2 Answers

The normal way to do this would be as follows:

router.post('/index', function(req, res) {   <<< 'next' removed (only needed if using middleware)

  // ...Get form values, do calculations to get toCost value.

  console.log('$' + toCost);

  res.render('indexTemplate', {cost: toCost}); <<< pass toCost through to jade as 'cost'
});

Then in your jade file for the indexTemplate you can reference the 'cost' variable passed in like this:

indexTemplate.jade:

extends layout

block content
  form(...)
  div#cost #{cost} <<< adds the cost variable to page

Then the value of toCost will appear in the resulting page.

No jQuery is required on the server side.

like image 178
jsdeveloper Avatar answered May 31 '26 08:05

jsdeveloper


jQuery is made for DOM manipulations and there's no DOM on a server. Try using 'jsdom'. jQuery is made for client side scripting, not for server-side client manipulations.

like image 30
siddhantsomani Avatar answered May 31 '26 10:05

siddhantsomani