Search code examples
javascriptnode.jsexpressejs

Send a request and re-render the page with the new data in EJS


I have different name data sent from server side by EJS, put in <a></a> tags:

<div>
     <% namesArr.forEach(name => { %>
         <a class="other-categories" data-doc="<%= name %>" id="<%= name %>">
            <%= name %>
         </a>
     <% }); %>
</div>

A chosen name would be used inside img.src to display image:

<div><img src="/imgs/<%=selectedName.replace(/\s/g,'%20')%>/<%=imgArr[i]%>"></div>

I hope when another name is clicked, the page somehow refreshes and re-renders with the specific name I click.

I don't know how to request something from client side to server side, I guess I would need new values such as {newSelectedName, namesArr, imgArr} for below code, since all values come from res.render by Express.js and database using Mongoose model:

Category.find()
.then(result => {
    #getNamesFunction
    #getImgArrFunction
    res.render('index', {selectedName, namesArr, imgArr})
})
.catch(err => console.log(err));

I was thinking to use fetch() and GET method to send a request again, maybe like this:

const otherCategories = document.querySelectorAll('.other-categories');
const endpoint = `/all-categories`;

otherCategories.forEach(category => {
    category.addEventListener('click', function(){
        fetch(endpoint, {
            method: 'GET'
        })
        .then(response => response.json())
        .then(data => #doSomeThing)
        .catch(err => console.log(err))
    })
})

I'm not even sure if this method makes sense, I feel like there is a way to get specific response by different request, so that it might be helpful in my situation.


Solution

  • There are many ways, I am sharing one of them

    1. routing

    You have to use two rout path one with param and one without param

    req.get("/image",(req,res)=>{res.render("image", {name:"nameFromServerSide"})})
    
    
    req.get("/image/:name",(req,res)=>{res.render("image", {name: req.params.name})})
    

    2.image.ejs

    you have to use <a></a> tag on every name you have

    <a href="/image/nameOfTheImage1"><button >nameOfTheImage1</button></a>
    <a href="/image/nameOfTheImage2"><button >nameOfTheImage2</button></a>