Skip to content

Instantly share code, notes, and snippets.

@sreepurnajasti
Last active January 27, 2023 00:51
Show Gist options
  • Save sreepurnajasti/e30d3c0e89ef66b4f35ecaaebf823c75 to your computer and use it in GitHub Desktop.
Save sreepurnajasti/e30d3c0e89ef66b4f35ecaaebf823c75 to your computer and use it in GitHub Desktop.
send form data from html form using jquery ajax(serialize method) to express Nodejs
<!doctype html>
<html>
<head>
<title>AJAX/Express Example</title>
</head>
<body>
<form id="signup" method="POST" action="/addUser">
<div>
<label for="name">Name</label>
<input name="name"type="text" id="name" />
</div>
<div>
<label for="email">Email</label>
<input name="email" type="text" id="email" />
</div>
<div>
<label for="mobile">Mobile</label>
<input name="mobile" type="text" id="mobile" />
</div>
<input type="submit" value="Submit" />
</form>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="/main.js"></script>
</body>
</html>
$('document').ready(() => {
$('#signup').on('submit', handleSignup)
function handleSignup (e) {
e.preventDefault()
const options = {
method: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
}
$.ajax(options).done(response => {
alert(JSON.stringify(response))
})
}
})
const path = require('path')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(express.static(path.join(__dirname, '/public')))
app.use(bodyParser.urlencoded({ extended: true }))
app.get('/', (req, res)=>{
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/addUser', (req, res) => {
const user = {
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile
}
console.log(user)
res.send(user)
})
app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment