Pass information submitted through a JavaScript prompt to an expressjs endpoint

I'm currently facing a challenge in extracting the value from my prompt in order to modify a category using a JavaScript function. Typically, I would rely on a form to pass variables to the request.body, but that's not an option here.

This is what my code looks like:

    <div style="margin-bottom: 2%; margin-top: 2%;">
        <% categorys.forEach(function(category){ %>
            <h2 style="display: inline;"><%= category.category_name %></h2>
            <a onclick="updateCategory()" class="update-category" href="/api/category/update/<%= category.category_id %>">Update</a>
            <a href="/api/category/delete/<%= category.category_id %>">Delete</a>
            <br>
        <% }); %>
    </div>

    <script>
        function updateCategory() {
            var category_name = prompt("Please enter category_name")
            var clickedOk = confirm("Are you sure you want to update?");
            $("#category_name").val() = category_name;
        }

    </script>

Here's an overview of how the data should be handled on the server side:

router.get('/update/:id', async(req, res) => {
    // Ensure user is authenticated before proceeding
    sess = req.session;
    if(!sess.authenticated) return res.status(401).send("Unauthorized please login.");
    console.log(req.body)
    if(!req.body) return res.send('empty body');

    const respUpdateCategory = await ourCategory.updateCategory(req.params.id, req.body.category_name)
    if(respDeleteCategory) {
        return res.status(201).send('Successful!')
    } else {
        return res.statusCode(400).send('Something went wrong!')
    }
});

Answer №1

I have never attempted this particular solution as I encountered backend issues that needed to be resolved first. However, one approach could involve creating a hidden input element with the name and id of category_name in the HTML code and then dynamically setting its value using JavaScript once certain conditions are met.

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

What is the best way to pass my request data to my $scope variable?

I'm currently facing a challenge with this particular topic. My goal is to add the response data that I retrieve from Express to my angular $scope and then direct the user to their profile page. This is how my Controller Function is structured: $sc ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

Drawing on Canvas with Html5, shifting canvas results in significant issues

I've been working on developing an HTML5 drawing app, and while I have all the functionality sorted out, I'm facing challenges during the design phase. My main issue is centered around trying to make everything look visually appealing. Specifical ...

Managing global HTTP response errors on Vue/axios using Vuex

I've encountered an issue in my VueJS SPA where a strange limbo state occurs. The application fails to recognize that the JWT token has expired, leading it to still display as if the user is logged in. This typically happens after periods of hibernati ...

Tips for setting a checkbox as checked by default using AngularJS

I would like the checkbox to be checked by default. HTML : <div class="form-group col-sm-6" ng-class="{ 'has-error': pForm.caddress.$dirty && pForm.caddress.$error.required }"> <label class="contro ...

Exploring Nested CSS Grids and Resizing Images on the Web

Having an issue resizing images in CSS Grid. I set up a main layout with 2 columns, and within the first column is another grid where I intended to place an image and some text. Please remove the html comment so you can see the image. The problem lies i ...

Creating an HTTP request inside an Export Function in a MEANJS application

Initially, I utilized the Yo MeanJs generator to kickstart my project. As a newcomer in the world of MeanJs, things are starting to look quite complex for me. Currently, my MeanJs application is supposed to retrieve data from an HTTP request but, unfortun ...

Is it possible for three.js to integrate information from REST APIs?

Currently, I am in the process of learning three.js and have successfully created basic 3D models using hardcoded values. My goal now is to retrieve these values from a database that I have set up in MSSQL Server. These x, y, and z parameters are stored ...

Activate onbeforeunload when the form is not submitted

Currently, I have a form that is submitted using PHP with three different submit actions: Save and Continue Save and Exit Exit without Saving The goal is to trigger an "OnBeforeUnload" alert if the user does not click on any of the form actions. This al ...

Common mistakes encountered when utilizing webpack for react development

I'm currently following the exercises in Pro MERN Stack by Apress and have come across a webpack issue. Everything was running smoothly until I introduced webpack into the mix. Now, when I execute npm run compile, I encounter the following error: > ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

Properly encoding strings in Node.js

In my NodeJS code, I am dealing with the following string: '3&#xAA; Jornada: Resumen 2' which is meant to be displayed as: '3ª Jornada: Resumen 2' I have attempted to convert it using the decodeURIComponent(escape(myString)) ...

Installing npm gets stuck on the Google Cloud Compute Engine virtual machine

I'm attempting to set up a Medusa backend on a Google Cloud Compute Engine VM. Whenever I run the command npm i --verbose, it gets stuck with the last line displayed as: reify:@swc/core-darwin-arm64: http fetch POST 200 https://registry.npmjs.org/-/np ...

Looking to include some extra padding when an item is displayed - jQuery

So, I'm working on a jQuery code snippet that controls the visibility of a rectangle element: $("#rectangle").hide(); $("#toggle-rec").click(function () { $("#rectangle").toggle(2000); }); This code hides the rectangle initially and toggles it ...

Adjust the background image color with CSS styling

I have a collection of icons that I would like to incorporate into my application. These icons primarily consist of glyphicons with a few others mixed in. I want the HTML structure to mimic that of a glyphicon, specifically: <a href="#"> <spa ...

What is the process for transmitting information via a Link in Next.js?

In my upcoming 13.1.5 version, I am faced with a challenge of sending the value of contact.name through a Link in my component. I am looking for the most effective approach to achieve this. The initial code block for the Link represents my original code. ...

Difficulty adding extra arguments to a function

I am currently working on a function in d3 that aims to evaluate the "time" of my data and determine if it falls within specific time intervals. This will then allow me to filter the data accordingly. //begin with a function that checks if the time for eac ...

Attempting to showcase information on the Angular frontend

When attempting to retrieve the Street name, I am seeing [object Object]. What is the optimal approach for displaying JSON data on the client side? I managed to display a street name but struggled with other components. How can I access the other elements ...

Creating a post request in Express.JS with an empty object

Currently, I am working with Express version 4.18.2. I have created routing and controller files along with an HTML form that uses the POST method. However, when I submit the form, I attempt to display the req.body object sent in the request through the co ...

Display the Bootstrap datepicker within an h4 element set to default to today's date, utilizing both Angular and jQuery

Utilizing Boostrap datepicker to obtain the selected date from the calendar and insert it into an <h4> html tag. However, my goal is to display today's date by default in the h4 when it opens for the first time. Using angular.js + jquery f ...