shiva
shiva

Reputation: 49

Get selected option value in node.js with using express

I need to get the selected object using express to console it in app.js

example.html

 <form id="tableForm" action="getJson">
        <select class="example" name="example">
              <option name="" value="0" selected>Select table</option>
              <option name="table1" value="1">Table 1</option>
              <option name="table2" value="2">Table 2</option>
              <option name="table3" value="3">Table 3</option>
        </select>
    </form>

App.js

var express = require('express'),
app = express();

app.use(express.bodyParser());

 app.get('/', function(req, res){
  res.sendfile('views/index.html');
});

app.get('/getJson', function (req, res) {
   console.log(req.body.example);
});

app.listen(3000, function(){
    console.log('Server running at port 3000: http://127.0.0.1:3000')
});

The output of the console is undefined even if I select another object.

Upvotes: 4

Views: 16245

Answers (3)

user7559884
user7559884

Reputation:

Here are the mistakes in your code

1)In HTML file , Your form should have a post method

<form method="post" id="tableForm" action="getJson">

(2) That post method should be handled in App.js . The input value given by the user can be collected by req.body.example method

Upvotes: 0

Muhammad Hammad
Muhammad Hammad

Reputation: 1

try this

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));

instead of

app.use(express.bodyParser());

Upvotes: 0

Sridhar
Sridhar

Reputation: 11786

You need to add handler for the post method on form submission.

app.js

app.post('/getJson', function (req, res) {
   console.log(req.body.example);
});

example.html

<form method="post" id="tableForm" action="getJson">
  <select class="example" name="example">
      <option name="" value="0" selected>Select table</option>
      <option name="table1" value="1">Table 1</option>
      <option name="table2" value="2">Table 2</option>
      <option name="table3" value="3">Table 3</option>
  </select>
</form>

Upvotes: 6

Related Questions