How to get dynamic parameter from html form in ajax - node.js

I have system for liking/unliking posts and I don't want page refresh to occur when user likes post. I want to use ajax to prevent that but don't know how to fetch
<form action="/posts/like/{{post.id}}" method="POST" id="like-form">
<button type="submit" id="like-button">Like</button>
</form>
How to fetch this {{post.id}} in ajax, I've tried using form.action but that returns whole url i just want id of certain post

You're not clear what are you using for the back-end like API built with Node or you're using templating engine with Node, but you can try this on front-end to achieve it.
document.querySelector('#like-form').addEventListener('submit', function(e) {
e.preventDefault(); // this prevents page refresh
fetch(`/posts/like/${post.id}`, { method: 'POST' });
});

Related

Passportsjs logout - document says to use app.post but fails saying "Cannot GET /logout"

The documentation for passport js https://www.passportjs.org/concepts/authentication/logout/ says..."It is a good idea to use POST or DELETE requests instead of GET requests for the logout endpoints, in order to prevent accidental or malicious logouts."
My code looks like this...
app.post('/logout', function(req, res){
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
The error I get when logging out is "Cannot GET /logout"
when I change the app.post to app.get it works no problem but that goes against what the documentation is suggesting. How do I get app.post to work?
You have to move that "logout button or link" inside your .ejs and put it inside a form, so you would be able to post that logout request.
Something like this:
<form class="" action="/logout" method="post">
<button class="" type="submit" name="button">Logout</button>
</form>
Share the code where you put the option for the user to logout and i will help with that too.

How to "catch" a form's post request status?

I am using Node.js(with express) to make a website and I'm pretty new at it. I am currently stuck on how to "catch"(not sure the proper term) a POST request response on the client side. I have a page that has a form that the user fills out. Once the user hit the submit button the server-side gets the information and process it. Then once done it sends a status code. What I want to do on the client side is "catch" that status code, depending on the code, if its good then redirect to the next page else pop up an alert to the user that something is wrong with their input(or something along those lines). If someone can show me the most simplest way of doing it, as I am still learning, I would appreciate it.
When I hit submit it changes my browser window blank with a text: 'OK'
index.html
<!DOCTYPE html>
<html>
<head><title>Index</title></head>
<body>
<form action="/create" method="POST">
<input type="text" name="input1" value="Message"></br>
<input type="number" name="input2" value="0"></br>
<input type="submit" value="Submit">
</form>
<script src="app.js"></script>
</body>
</html>
app.js
//where I want to "catch" my post request response
index.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(express.static(__dirname+'/views'))
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.post('/create', function(req, res){
//abstract data and send to db
if(okay)
res.sendStatus(200)
else
res.sendStatus(400)
})
When I hit submit it changes my browser window blank with a text: 'OK'...why can't I use a HTML form submission?
That's because if it is a plain HTML form submission, the browser will send the HTTP request, get response from server, and display that response content as a new web page (and replace the old one).
Why I have to use an Ajax request?
To get resonse from server without refresh the page, you need to send an Ajax request. That is, send the HTTP request via JavaScript, rather than via HTML element. In this way, the response can be processed by JavaScript code ("if its good then redirect to the next page else pop up an alert").
Example Ajax code is listed as below (using jQuery):
$.post('/create', {
input1: 'Message',
input2: 0
}).done(function(){
// redirect to the next page.
}).fail(function(){
// pop up an alert
});

Render view as result of POST request in Express

I have a basic node app which is integrated with stripe. The client-side javascript generates a token which is sent in a POST request to the server. The server then sends the stripe API the token which makes the payment. I want to redirect the user to a page showing some info e.g. Payment successful or Error making payment.
When I put res.render("/charge", {<some-JSON>}); in the code that handles the POST request, it sends the page /charge as a response to the POST request. Is there a way to send the user a page as a response instead of sending the POST request the response?
Node Snippet:
app.post(req, res) {
// Some Code
}
From what I gather from your post and comments. You are looking for a way to display Stripe response data into your webpage.
Instead of doing your traditional AJAX request with client-side JavaScript, use a form to submit the data to your server-side.
<form action="/stripe" method="post">
<input type="text" value="whatever" name="batman">
<button type="submit">Pay</button>
</form>
On your server-side, create an endpoint, using app.use('/stripe'), as an example, but the endpoint has to match your value in the action="" attribute. Then simply render the page with the stripe response.
app.use('/stripe', function(req, res) {
// whatever code
res.render('/charge', {JS OBJECT});
});

Don't redirect on POST express.js

I'm making a basic web app with Node.js and Express 4 and I'm trying to implement a "follow" function. I did some inspecting on the Github website and noticed it used a form with a follow button that would post to the server to follow a user. I think this sounds like a good approach but when I post I don't want to have to reload the page just like the github website.
How does one this inside of Express 4? Everything I put inside the .post route always end up in a page load. I'm pretty sure in jQuery's ajax method you can just return false and nothing will happen to the page, just the request will be sent which is what I want to happen because I'm using a RESTful api and I want to add the user to the current user's following but I don't want to have to use jQuery just for this function. I would prefer it be done in Express if possible, though any help would be appreciated.
views/user.handlebars
<h1>{{user.displayName}}</h1>
<p>#{{user.username}}</p>
<form action="" data-userid="{{user._id}}" method="post">
<button name="follow" type="submit">Follow</button>
</form>
routes/users.js
app.route('/:username')
.get(function(req, res) {
// get :username user from api and load info
...
})
.post(function(req, res) {
// don't reload page
???
// send PUT :username user to current users following array
...
});
So you're on the right track, but instead of putting your actions in the HTML (in your jade file) you're gonna have to add a script section to your jade and use javascript to attach an onClick event to the button so that when you press the button you invoke your ajax method.
Let me know if that doesn't make sense.

res.send() express.js automatically redirect

I am using nodejs and the framework express.js to realize my website.
I am submitting a POST request on an url (/report/reportname) reportname is a variable.
so I do this :
app.post('/report/:id', function(req, res){
var id=req.param('id');
var bodyreportHtml;
go.prototype.runReport(id,res);
}
The thing is that in go.prototype.runReport(id,res)
I do a res.send(bodyofthereport).
So when I click on submit on my form that just redirect me on /report/nameofthereport where the pdf report is.
Everything is working but I would like to put this url /report/nameofthereport (the pdf report) in an iframe.
So when I submit the post request I want it just refresh the iframe and print the report in it ( the iframe is on the same page than the form).
But the res.send(bodyofthereport) is essential : it prints my report at /report/nameofthereport
And I can't do a res.redirect('/') because the body is finished
How can I do ?
Thanks !
If you want to POST to an iframe, you could just set the target attribute of the form to the name of the iframe:
<form action='/report/ID' method='POST' target='FOO'></form>
<iframe name='FOO'></iframe>
Nothing node.js or Express specific about this!

Resources