Eduard
Eduard

Reputation: 9165

Passing a variable from .ejs file back to express.js

I am working upon the project using node.js with express.js framework and view engine set to "ejs". The project's functions is to:
1. Get an input from a user.
2. Using the input send the request to the website's API.
3. Print the certain data from that API (including the ID to be used later).
4. When user clicks on the item (that is an 'a' tag) in the list consisting of the aforementioned data - use the ID of this item to send another request to the same website to get a more detailed info about the item.

I am stuck at the step 4. And the question is:
How to send this id from the .ejs file to post request in node.js when the user clicks on the item?
Doing it the other way is simple: response.render("view name", {nodeJsVar: ejsVar}); But how to pass it back?
Thanks for the help!

Upvotes: 0

Views: 2343

Answers (2)

rsp
rsp

Reputation: 111336

First of all, you cannot send any data "from the .ejs file" - what you can do is to send it from the browser, that has a rendered HTML (and possibly JavaScript) and not EJS.

You can do it with some client-side JavaScript in which case you can do whatever you want.

You can do it by embedding the variable's value in a URL as a route parameter or a query parameter if you're using standard <a href="..."> links.

You can put a hidden input in a form if you're using forms and buttons.

You can put it in any part of the request if you're using AJAX.

Just to make sure you know what is what because it can be confusing - here X is a path parameter:

http://localhost/something/X

and here X is a query parameter:

http://localhost/something?x=X

Upvotes: 3

schaffioverflow
schaffioverflow

Reputation: 510

try this (assuming you use jQuery):

$.ajax({
  url: '/routename_to_handle_id',
  type: 'POST',
  data: { id: id }
}).done(function(response){
 //callback to handle if it's successful
})

Upvotes: 0

Related Questions