I use node.js and express. When I press the button (btnSend), I want to send data to node.js by express (without refresh the page). How do I send data using jQuery?
<form action="/Send" method="post">
Username:
<input type="text" name="user" id="txtUser" />
<input type="submit" value="Submit" id="btnSend" />
</form>
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 code snippet finds all form elements on the page and listens for a submit event from them. A form can be submit in a number ways (e.x. clicking a submit button, hitting enter, etc...), so for the sake of usability, it's best to listen for submit events directly opposed to listening for click events key on submit buttons.
When a submit event does occurs, the code above first prevents the default browser actions (which among other things refreshes the page) by calling e.preventDefault
. It then uses $.post to send the form data to the url specified in the action attribute. Note that $.fn.serialize
is used to serialize the 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 on express.bodyParser
is a bit sparse, but after a bit of code spelunking it looks like it uses node-querystring underneath the covers.
Hope this helps!