Skip to content

Instantly share code, notes, and snippets.

@kanakiyajay
Created February 25, 2014 16:39
Show Gist options
  • Save kanakiyajay/9212632 to your computer and use it in GitHub Desktop.
Save kanakiyajay/9212632 to your computer and use it in GitHub Desktop.
Ajax forms using express.js and jQuery utilizing mysql and node-js
var mysql = require("mysql"),
express = require("express"),
app = express();
var connection = mysql.createConnection({
host : "localhost",
user : "root",
password : "",
database : "node"
});
connection.connect();
app.use(express.bodyParser());
app.get("/",function (req,res) {
res.sendfile(__dirname+"/index.html");
})
//connection.end();
app.post('/', function(req, res){
console.log(req.body);
connection.query("INSERT into sample SET ?",req.body,function (err,result) {
if (err) throw err;
res.send("Created "+JSON.stringify(result));
});
//res.send("Received"+req.body)
});
app.listen(3000);
console.log("listenening on 3000");
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mysql Editor</title>
</head>
<body>
<form id="submit" method="post" action="/">
<input type="text" name="first" placeholder="First-name"><br>
<input type="text" name="last" placeholder="Last-name"><br>
<input type="text" name="nick" placeholder="Nick-Name"><br>
<input type="number" name="extras" placeholder="Extras"><br>
<input type="submit" value="Submit">
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#submit").on("submit",function (e) {
e.preventDefault();
console.log();
$.post("/",$(this).serialize(), function( data ) {
console.log(data);
});
})
});
</script>
</body>
</html>
@Ging123
Copy link

Ging123 commented Apr 18, 2021

thank you dude, this code help a lot to understand how to get a response in my ajax. I was trying to do this for days
(sorry about my english, I´m not a native speaker)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment