node.js/express making post request without redirecting from current page
12,803
As a comment said, you need to use client side javascript+ajax.
$(function() {
$('#newEntryForm').submit(function(event) {
event.preventDefault(); // Stops browser from navigating away from page
var data;
// build a json object or do something with the form, store in data
$.post('/addEntry', data, function(resp) {
alert(resp);
// do something when it was successful
});
});
});
Comments
-
RagHaven over 1 year
I have a node.js express application which is trying to make a post request and query the contents of a database. I am trying to execute the post request without have to redirect the user from the form page or reloading the page.
index.jade
form.well(id="newEntryForm", method="post", action="/addEntry") label Key: br input(name="key", id="key", class="new-entry", type="textbox") br br label Value: br input(name="value", id="value", class="new-entry", type="textbox") br br button.btn(type="submit") Add Entry
app.js
app.post('/addEntry', function(req, res){ //database query });
This ends up redirecting me to the URL
localhost:3000/addEntry
. I know I can addres.redirect("/");
within the callback for the post method, but that will reload the page. How do I accomplish this without reloading the page?EDIT
I added a javascript method to execute on submitting the form, but it ends up appending the POST request parameters on the URL bar. How do I avoid this?
Javascript method
$(function() { $('#newEntryForm').submit(function() { var data = {key: 'a', value: 'b'}; // build a json object or do something with the form, store in data $.post('/addRule', data, function(resp) { alert(resp); console.log("post response: " + resp); // do something when it was successful }); }); });