0

I have just started out working with JS and I've managed to post data from a MySQL db to the website using node.js, jade and plain JS.

Now I'm trying to do the other way around, i.e. getting data from the website, to the JS code and then inserting it into the db.

What I'm thinking is simply making a textfield with a button. When I fill the textfield and press the button it is collected by the JS script and the inserted to the DB.

I am however having problems with Jade and the listener and I'm unable to even do a console.log using the listener.

This is what I've got so far in my .jade file.

extends layout

script.
  var something = function() {
    console.log('something')
  }

block content
  button(onclick='something()') Click

The website renders nicely, but nothing is printed when I click the button.

If someone could give a hint on how to fetch the data in my .js file that would also be appreciated.

Willy G
  • 1,172
  • 1
  • 12
  • 26
  • Why is this tagged `node.js` when you appear to be generating *client side* JavaScript? Why are you dealing with client side JavaScript when your ultimate goal is to insert something into a database on your server? – Quentin May 24 '16 at 14:59
  • I tagged it as node.js because that's what I'm using to control the views etc. Sorry, but I'm new to this and maybe node.js isn't relevant to the question. As for your second question: I have no idea. I'm very new to this and what I'm doing might be (and probably is) worst practice. – Willy G May 24 '16 at 15:00
  • 1
    You need to look into AJAX to send the data back to the server – theaccordance May 24 '16 at 15:01

1 Answers1

1

In the context of the WWW there are two places that JavaScript can run.

  1. On the server, e.g. with node.js
  2. On the browser, embedded in a <script> element

Since you want to put the data into a database on the server, you want to go with option 1. So don't use a <script> element.

Use a <form> (you could use client side JS to read the data from the form and send it to the server (Ajax) but that seems overcomplicated for your needs and should be layered on top of a plain HTML solution if you were to go down that route).

form(action="/myendpoint" method="post")
    label
        | Data
        textarea(name="foo")
    button Submit

Then you just need to write server side code to retrieve that. The specifics of that will depend on how you are implementing the HTTP server in Node.

The question How do you extract POST data in Node.js? provides some starting points.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335