Skip to content Skip to sidebar Skip to footer

Send Data From Ajax GET To Ejs File

I am retrieving some user data with an ajax GET call, and want to display each user in a bootstrap card, so that I can filter these on the page using jQuery. Currently, I get the

Solution 1:

You need to implement an endpoint that fetches user information and forms the template for your userList div and sends the data back as a plain html string.

This endpoint has to be called from the client via an ajax call and set the response html to the div

Server

    app.get('/api/user/all',(req, res){
   //get user data
   const data = [{username:"john",jobTitle:"a",city:"b"},{username:"doe",jobTitle:"a",city:"b"}];

   res.render('userTemplate', {users:data} ,function(err, html) {
      res.send(html);
  });

Client

$.ajax({
  url: "/api/user/all",
  cache: false,
  success: function(html){
    $("#userList").innerHtml(html);
  }
});

userTemplate.ejs

<% for(var i=0; i < users.length; i++) { %>
    <div class="col-md-auto mb-4">
        <div class="card matches mx-auto" style="width: 18rem; height: 24rem;">
            <div class="card-body">
                <h5 class="card-title"><%= users[i].username %></h5>
                <p class="card-text"><%= users[i].jobTitle %></p>
                <p class="card-text"><%= users[i].city %></p>
            </div>
        </div>
    </div>
 <% } %>

Solution 2:

EJS is server-side code.

If you want to generate your HTML server side instead of modifying the DOM client side, then replace getJSON with an ajax call (with dataType: "html") and change /api/user/all to an endpoint (which you will have to create) which gets the data and inserts it into an EJS template.


Post a Comment for "Send Data From Ajax GET To Ejs File"