Willy G
Willy G

Reputation: 1252

Retrieving data from browser to JavaScript

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.

Upvotes: 0

Views: 56

Answers (1)

Quentin
Quentin

Reputation: 943635

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.

Upvotes: 1

Related Questions