Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm struggling to make a function which selects from database based on the id entered in a textbox. I wrote the code, but it shows in console this error and I can't figure why:
TypeError: Cannot read property 'id' of undefined
.
Code I have so far:
Client-side:
function select()
var id = $('#nr_reg').val();
$.ajax({
type: 'post',
url: '/id',
data : {
id: id
succes: function(data){
var id = data.id;
alert(id);
$('#optic').val(id);
error: function(err){
console.log(err);
Server-side:
app.post('/id', function(req,res) {
var data = req.body;
var id = data.id;
console.log(id);
var query = "SELECT * FROM Control WHERE id=" +id;
connection.query(query, function(error, result) {
console.log(result);
res.send(result);
Function select:
function select()
var id = $('#nr_reg').val();
$.ajax({
type: 'post',
dataType: 'json',
url: '/id',
data : {
id: id
success: function(data){
data = JSON.parse(data);
var id = data.id;
alert("merge");
$('#optic').val(id);
error: function(err){
console.log(err);
–
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
This should be before your .post
route definition.
EDIT:
Before all this, you must do npm install body-parser
:)
–
–
–
–
You said your error is on server side? Add a body parser to your express app:
1st Install body-parser:
npm install body-parser -s
The include this in your app:
var express = require('express');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post(/*....*/);
Your app.post
must be AFTER app.use
line.
Full example here
BTW this is a duplicate of this
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.