Displaying an ejs file on the client's side

Struggling to implement AJAX functionality for cloning an 'item' template. I am attempting to insert an EJS template containing information about the newly cloned item into the main EJS page after each POST request. However, I am having difficulty finding the correct approach to achieve this. I have carefully followed the documentation and have the front-end EJS script in place.

Currently encountering the following error: resp is not defined

The 'itemDisplay' template is used to display all items, and 'inventory-scroll-list' is the div containing all items. 'resp' represents the newly created/cloned item (from Mongoose).

// Cloning item using AJAX (to display new item)
$('.cloneItemButton').click(function () {
    const itemId = $(this).attr('id')
    $.ajax({
        method: 'POST',
        url: '/item/' + itemId + "/clone",
        success: function (resp) {
            console.log('Item Cloned: ' + resp._id)
            var html = ejs.render('<%- include("/itemDisplay",  { item: resp }); %>')

            $('.inventory-scroll-list').append(html)
        },
    })
})

Answer №1

const content = ejs.render('<%- include("/itemDisplay",  { item: resp }); %>');

The variable resp contains a string and cannot be used since the /itemDisplay file is not accessible in the browser.

If the ejs file is standalone and doesn't rely on other ejs files, you can directly assign its content to a variable.

const template = 'The complete content of the ejs file';
const html = ejs.render(template, { item: resp });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

404 error message generated by an Express route

I am encountering a 404 error on the express route of my node app. While it functions correctly locally, upon deployment to the production server, it begins returning the 404 error (please note that I have updated the AJAX URL to match the one on the produ ...

Upon sending a POST request to http://localhost:5000/getData, a 404 error (Not Found) was encountered while using axios

As a newcomer to react and node.js, I have set up a fake server running on port 5000 with an API (http://localhost:5000/getData) that contains a hardcoded array of objects. My goal is to add a new object to this API from my react frontend running on port 3 ...

An incorrect object was removed from the array

Having an issue where the wrong item is getting deleted from an array in my component's state. Here is a simplified version of my parent Component: export default class BankList extends Component { state = { banks: [new Bank("Name1"), new ...

Retrieving information from Firebase using React

Is there a way to retrieve data from Firestore? import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; const firebaseConfig = { apiKey: "AIzaSyCNBAxjeKNoAPPjBV0 ...

In Flow, how is the asterisk (*) type utilized and what is its counterpart in TypeScript?

My expertise lies mostly in TypeScript, but I recently came across Flow which seems quite similar to TS in many aspects. However, one thing that caught my attention is the asterisk (*) type in Flow. Initially, I thought it was just another way of represent ...

RxJS emits an array of strings with a one second interval between each emission

Currently, my code is set up to transform an Observable<string[]> into an Observable<string>, emitting the values one second apart from each other. It's like a message ticker on a website. Here's how it works at the moment: const ...

preventing users from selecting past dates on Full Calendar Plugin

Is there a way to disable the previous month button on the full calendar? Currently it is April. When I click on the previous button, the calendar shows March instead of disabling. How can this be prevented? http://jsfiddle.net/6enYL/ $(document).ready( ...

Issues with Ionic's $state.go and ui-sref functions not functioning as expected in the app

While attempting to change the view on the Ionic View app for iOS (I have not tested on the Android app), I encountered a bug that seems to have a solution, but unfortunately, it does not work for me. Bug info: Bug info 2: My Ionic information is as fol ...

Utilize filtering techniques on a nested system

After creating an Angular app to display a hierarchy, I am now attempting to add a text box on top of the hierarchy for data filtering purposes. Despite trying various filter examples, I have not achieved much success. My goal is to implement Angular bind ...

Issue with Firefox compatibility in Backbone.js

Greetings! I am currently utilizing Backbone.js and require.js for my application, experiencing difficulty with template rendering in Firefox. Interestingly, it works without issues in both Chrome and IE. Allow me to present the code responsible for rende ...

Exploring an array in Angular 2 using TypeScript

Just starting out with typescript and angular2 and working through some issues. I have a form that needs to display results from an array of changing items, so I don't know the exact index of each result. Here is my scenario: In my form.html file: ...

How should dates be formatted correctly on spreadsheets?

Recently, I have been delving into Google Sheets formats. My approach involves utilizing fetch and tokens for writing data. rows: [{ values: [ { userEnteredValue: { numberValue: Math.round(new Date().getTime() / 1000) }, userEnteredFormat: { ...

Tips for utilizing a function within a callback function using jQuery

When using jQuery's .load() to load HTML files into a parent webpage, I am interested in executing jQuery/JS from the parent page against the loaded HTML file. It seems like this can be achieved with a callback function. The jQuery I'm using is ...

retrieving the webpage's HTML content from the specified URL using AngularJS

Utilizing the $http.get('url') method to fetch the content located at the specified 'url'. Below is the HTML code present in the 'url': <html> <head></head> <body> <pre style = "word-wrap: break ...

Tips for combining two htmlelements together

I have two HTML table classes that I refer to as htmlelement and I would like to combine them. This is similar to the following code snippet: var first = document.getElementsByClassName("firstclass") as HTMLCollectionOf<HTMLElement>; var se ...

Warning: npm is resolving peer dependency conflicts during the installation process

Upon running npm install for my React application, I encountered the following warnings in the logs. Despite that, the npm installation completed successfully and the dependencies were added under node_modules. My app even starts up without any issues. I ...

Inputting model variables into a Mongoose schema

One issue I have is with a mongoose model that has an association with a user model. Here's the code snippet: var exampleSchema = mongoose.Schema({ name: String, <some more fields> userId: { type:mongoose.Schema.Types.ObjectId, ref: &a ...

How can you organize an array into rows and columns for easier viewing?

Hopefully everything is clear. I am open to making changes if needed to address any important points. In one of my components, the array items are displayed within cards as shown below: <b-card-group deck class="mb-3"> <b-card border-variant ...

Guide to extracting a key from the route module with the help of vuex-router-sync

I have a Vuex store setup as shown below, and I am using vuex-router-sync to keep it in sync. This plugin adds a router module to my store. However, I am unsure of how to retrieve this object from the store since there are no associated getters with this m ...

Tips for detecting the creation of an iframe before executing any javascript code

Before executing some JavaScript, I am trying to wait for an iframe to be created. I have attempted several methods, but none seem to effectively wait for the iframe. The console error that keeps appearing is Uncaught (in promise) TypeError: Cannot read pr ...