0

So this is my server.js file, where the db is being connected to :

var app = require('express')();
var mysql = require('mysql');
var db = mysql.createConnection({

    host: 'localhost',
    user: 'root',
    password: '',
    database: 'user_data',
    port: 3306
});
db.connect();

app.get('/', function (req, res) {
    res.sendFile(__dirname + "/start.html");
});

app.listen(3000);

So I want to make something like a registration form, where you input your username and password. Then, after you click the submit button, the username and password are supposed to go straight to the mySQL database. So apparently, I need an ajax call which sends the data to that server, but I don't know how to access it on the server.js.

$("button#submit").click(function () {
      $.ajax({
           'url': 'http://localhost:3000',
           'type': 'post',
           'data': {
                'username': $("#usr").val(),
                'password': $("#pwd").val()
           },
           'success': function (data) {
                alert('Data: ' + data);
           }
        });
  })

After I get that data on the server.js, I will obviously want to make a query (to insert the values) but how do I get the data?

1
  • mhm? any ideas? Commented Mar 23, 2017 at 10:11

1 Answer 1

1

This is how I did it for one of my projects:

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Contact Form</title>

</head>
<body>
<div id="contact">
    <h1>Send an email</h1>
    <form action="/myaction" method="post">
        <fieldset>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" placeholder="Enter your full name" />

            <label for="location">Location:</label>
            <input type="text" id="location" name="location" placeholder="Enter your location" />

            <input type="submit" value="Send message" />

        </fieldset>
    </form>
</div>
</body>
</html>

Now when user clicks submit /myaction url will hit.

db.connect(function(err,connection){
    app.post('/myaction',function(req,res){
    console.log(req.body);

     var employee={name:req.body.name,location:req.body.location}

    db.query('INSERT into employees SET ?',employee,function(err,res){
    if(err){
        throw err;
    }
        else{
        console.log(res);

    }


        })
   res.send(JSON.stringify(req.body));
})
})

Make sure to include these in your server.js

var express=require('express');
var bodyParser=require('body-parser');
app=express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

So you can see i have defined app.post and I am hitting my url. Then we simply write a sql query to store data.

Sign up to request clarification or add additional context in comments.

18 Comments

Interesting. Thank you. I will try this out
Well, req.body.name is undefined
or to be more specific, req.body is
req.body is the data you are sending to server, so for name req.body.name.
for you it will be req.body.username. Is req.body showing up or req.body is also undefined.?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.