Node.js - submit a form

I use node.js and express. When I click the (btnSend) button, I want to send data to node.js express (without refreshing the page). How to send data? Using jquery?

Please, help.

Thanks for the advice.

<form action="/Send" method="post"> Username: <input type="text" name="user" id="txtUser" /> <input type="submit" value="Submit" id="btnSend" /> </form> 
+7
source share
1 answer

Here's a rough outline of what your jQuery should look like:

 $("form").submit(function(e) { e.preventDefault(); // Prevents the page from refreshing var $this = $(this); // `this` refers to the current form element $.post( $this.attr("action"), // Gets the URL to sent the post to $this.serialize(), // Serializes form data in standard format function(data) { /** code to handle response **/ }, "json" // The format the response should be in ); }); 

This piece of code finds all the form elements on the page and listens for the submit event for them. A form can be represented in several ways (for example, by pressing the submit button, pressing the enter button, etc.). Therefore, for ease of use, it is best to listen to send events that are directly opposite to listening to the event keys for pressing the send buttons.

When a send event occurs, the code above first prevents the default browser (which, among other things, refreshes the page) by calling e.preventDefault . Then he uses $. Post to send form data to the url specified in the action attribute. Note that $.fn.serialize used to serialize form data in a standard format.

Your express code should look something like this:

 var express = require('express') , app = express.createServer(); app.use(express.bodyParser()); // Automatically parses form data app.post('/Send', function(req, res){ // Specifies which URL to listen for // req.body -- contains form data }); app.listen(3000); 

The documentation for express.bodyParser bit sparse, but after a bit of spelunking code, it looks like it uses node-querystring under the covers.

Hope this helps!

+15
source

All Articles