javascript - Sending Form Data to Node Server -
i trying send form data endpoint.
here's client side code:
<form name="form" action="http://localhost:8080/geodata" method="post"> <label for="minlat"> minlat: </label> <input type="text" name="minlat" value="0"><br> <label for="maxlat"> maxlat: </label> <input type="text" name="maxlat" value="1"><br> <label for="minlong"> minlong: </label> <input type="text" name="minlong" value="0"><br> <label for="maxlong"> maxlong: </label> <input type="text" name="maxlong" value="1"><br> <button type="submit" class="btn btn-success"> submit <span class="fa fa-arrow-right"></span></button> </form> <script> $(document).ready(function() { $("#form") .submit(function(event) { var formdata = { 'minlat' : $('input[name=minlat]').val(), 'maxlat' : $('input[name=maxlat]').val(), 'minlong' : $('input[name=minlong]').val(), 'maxlong' : $('input[name=maxlong]').val() }; $.ajax({ url: $form.attr('action'), data: formdata, cache: false, datatype: 'json', processdata: false, type: 'post', }).done(function(data) { console.log(data); }); event.preventdefault(); }); }); </script>
i have enpoint on server side code (express.js):
var express = require("express"); var path = require("path"); var bodyparser = require("body-parser"); var app = express(); app.use(express.static(__dirname + "/public")); app.use(bodyparser.json()); // initialize app. var server = app.listen(process.env.port || 8080, function () { var port = server.address().port; console.log("app running on port", port); }); app.post("/geodata", function(req, res) { console.log(req.body); res.send("hi"); });
i wish send form data endpoint /geodata, , use data send result client side. first of all, when hit submit, empty {} in terminal (which server side request.body). expecting form values in request.body don't receive them. how make sure form values being sent?
secondly, res.send("hi") re-directs initial page new page , prints "hi" there. since had made ajax call, shouldn't response logged , webpage stays on initial page?
change form action '/geodata'(the endpoint)
also dont need make ajax request html5 forms perform request if tag() pressed/clicked.
after click summit page become ever response sent '/geodata' route , req.body return object represents form data
Comments
Post a Comment