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:
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:
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!