Last active
January 27, 2023 00:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('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)) | |
}) | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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