What is the best approach to transfer information from the client side to a node

I have an ejs page that looks like this:

<%- include('../blocks/header', {bot, user, path}) %>
<div class="row" style="min-width: 400px;">
  <div class="col" style="min-width: 400px;">
    <div class="card text-white mb-3" >
      <%- include('../blocks/guild-nav', {active: "manage", guild}) %>
      <table class="table table-hover">
        <thead>
          <tr>
            <th scope="col">Setting Name</th>
              <th scope="col">Current Setting</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row" class="list-group-item d-flex justify-content-between align-items-center"
              data-toggle="tooltip" title="prefix"> Prefix<font color="red">*</font> </th>
              <td width="80%"><input type="text" class="form-control form-control-sm" style="text-align: left;"
                name="Prefix" id="Prefix" value="<%= prefix %>" placeholder="Enter prefix "></td>
          </tr>
          <tr>
            <th scope="row" class="list-group-item d-flex justify-content-between align-items-center"
              data-toggle="tooltip" title="welcomeChannelID"> welcomeChannelID </th>
              <td width="80%"><input type="text" class="form-control form-control-sm" style="text-align: left;"
                name="welcomeChannelID" id="welcomeChannelID" value="<%= welcomeChannelID %>"
                placeholder="Enter welcomeChannelID "></td>
          </tr>
          <tr>
            <th scope="row" class="list-group-item d-flex justify-content-between align-items-center"
              data-toggle="tooltip" title="logchannelID"> logchannelID </th>
              <td width="80%"><input type="text" class="form-control form-control-sm" style="text-align: left;"
                name="logchannelID" id="logchannelID" value="<%= logchannel %>" placeholder="Enter logchannelID ">
          </tr>
          <tr>
            <th scope="row" class="list-group-item d-flex justify-content-between align-items-center"
              data-toggle="tooltip" title="voicelogchannelID"> voicelogchannelID </th>
              <td width="80%"><input type="text" class="form-control form-control-sm" style="text-align: left;"
                name="voicelogchannelID" id="voicelogchannelID" value="<%= voicelogchannel %>"
                placeholder="Enter voicelogchannelID "></td>
          </tr>
          <tr>
            <th scope="row" class="list-group-item d-flex justify-content-between align-items-center"
              data-toggle="tooltip" title="defaultchannelID"> defaultchannelID</th>
              <td width="80%"><input type="text" class="form-control form-control-sm" style="text-align: left;"
                name="defaultchannelID" id="defaultchannelID" value="<%= defaultchannelID %>"
                placeholder="Enter defaultchannelID "></td>
          </tr>
          <tr>
            <th scope="row" class="list-group-item d-flex justify-content-between align-items-center"
              data-toggle="tooltip" title="guildautoroleIDt"> guildautoroleID</th>
              <td width="80%"><input type="text" class="form-control form-control-sm" style="text-align: left;"
                name="guildautoroleID" id="guildautoroleID" value="<%= guildautorole %>"
                placeholder="Enter guildautoroleID "></td>
          </tr>
          <tr>
            <th scope="row" class="list-group-item d-flex justify-content-between align-items-center"
              data-toggle="tooltip" title="playervolume"> playervolume</th>
              <td width="80%"><input type="text" class="form-control form-control-sm" style="text-align: left;"
                name="playervolume" id="playervolume" value="<%= playervolume %>" placeholder="Enter playervolume ">
          </tr>
          
        </tbody>
      </table>
      <div style="width: 100%; text-align: right; margin-top: 20px;">
        <a class="btn btn-danger" data-toggle="modal" data-target="#settingsResetModal" role="button">Reset Defaults
          <i class="fa fa-fw fa-cogs" aria-hidden="true"></i></a>
        <button type="submit" class="btn btn-primary" role="button">Save Changes <i class="fa fa-fw fa-save"
            aria-hidden="true"></i></button>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
  var guildID = "<%= guild.id %>";
  let data = {
    prefix: $('#Prefix').val(),
    welcomeChannelID: $('#welcomeChannelID').val(),
    logchannelID: $('#logchannelID').val(),
    voicelogchannelID: $('#voicelogchannelID').val(),
    defaultchannelID: $('#defaultchannelID').val(),
    guildautoroleID: $('#guildautoroleID').val(),
    playervolume: $('#guildautoroleID').val(),
  }
  $('.btn-primary.btn').click(function() {
            $.ajax({
                url: `/dashboard/${guildID}/set`,
                type: "POST",
                dataType: "json",
                data: JSON.stringify(data),
                contentType: "application/json",
                cache: false,
                timeout: 5000,
                complete: function() {
                  //called when complete
                  console.log('process complete');
                },

                success: function(data) {
                  console.log(data);
                  console.log('process sucess');
               },

                error: function(e) {
                  console.log(e)
                  console.log('process error');
                },
              });
        })
</script>
<% include ../blocks/footer %>

I tried sending the text to my node, but the data I am receiving is the data I sent to that site, not the new fresh edited by user. My dashboard.js file looks like this. All methods that send data to the client work, but I am stuck here:

app.get("/dashboard/:guildID/set", checkAuth, async (req, res) => {
    const guild = client.guilds.get(req.params.guildID);
    if (!guild) return res.status(404);
    const isManaged = guild && !!guild.member(req.user.id) ? guild.member(req.user.id).permissions.has("MANAGE_GUILD") : false;
    if (!isManaged && !req.session.isAdmin) res.redirect("/");

    if(welcomeChannelID !== `<#${(req.body.welcomeChannelID).replace(/[^0-9a-zA-Z_]/g, '')}>`) welcomeChannelID = `<#${(req.body.welcomeChannelID).replace(/[^0-9a-zA-Z_]/g, '')}>`
    db.collection('guilds').doc(guild.id).update({
      'prefix': req.body.prefix,
      'welcomeChannelID': welcomeChannelID.slice(2,-1) ,
      'logchannel': logchannel.slice(2,-1),
      'voicelogchannel': voicelogchannel.slice(2,-1),
      'guildautorole': guildautorole.slice(2,-1),
      'defaultchannelID':defaultchannelID.slice(2,-1),
      'playervolume': req.body.playervolume,

    })
    res.send(req.body);
    res.redirect("/dashboard/"+req.params.guildID);
  });

I removed the other defined variables, only here all are there in main code.

Am I missing something?

Answer №1

The problem arises from the javascript code within your script tags that only executes during page initialization.

This means that the value of the data variable is determined by the HTML Elements at the time the script runs.

let data = {
    prefix: $('#Prefix').val(),
    welcomeChannelID: $('#welcomeChannelID').val(),
    logchannelID: $('#logchannelID').val(),
    voicelogchannelID: $('#voicelogchannelID').val(),
    defaultchannelID: $('#defaultchannelID').val(),
    guildautoroleID: $('#guildautoroleID').val(),
    playervolume: $('#guildautoroleID').val(),
  }

So, if you want to retrieve the most up-to-date data, you need to fetch it when the button is clicked. Here's an example:

function getData() {
    return {
        prefix: $('#Prefix').val(),
        welcomeChannelID: $('#welcomeChannelID').val(),
        logchannelID: $('#logchannelID').val(),
        voicelogchannelID: $('#voicelogchannelID').val(),
        defaultchannelID: $('#defaultchannelID').val(),
        guildautoroleID: $('#guildautoroleID').val(),
        playervolume: $('#guildautoroleID').val(),
    }
}

$('.btn-primary.btn').click(function() {
    $.ajax({
        url: `/dashboard/${guildID}/set`,
        type: "POST",
        dataType: "json",
        data: JSON.stringify(getData()),
        ...
    } ... )
})

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

Encountering an error with [object%20Object] when utilizing ajaxFileUpload

I wrote a JavaSscript script that looks like this: $.ajaxFileUpload({ url: url, secureuri: false, fileElementId: ['upload-file'], dataType: "JSON", data:{ "sample_path":$(".demo-view-container-left .vie ...

The function is defined, but it cannot be set to null

Having trouble understanding this error message "Cannot set properties of null." I'm attempting to update the innerHTML with the output text from four functions that my button triggers. However, it seems to be stopping at the first function now even t ...

Issue: Attempting to access the `userName` property on an undefined object (`tem`), resulting in a TypeError while using flalist

A concern has arisen with the React Native Flatlist as it fails to render properly. What steps should be taken in this scenario? Below is the code snippet for reference: Image description available here import React, {useState, useEffect} from 'react ...

Can phantomJS be used to interact with elements in protractor by clicking on them?

While attempting to click a button using PhantomJS as my browser of choice, I encountered numerous errors. On my first try, simply clicking the button: var button = $('#protractorTest'); button.click(); This resulted in the error: Element is ...

Iterate through a Mongoose object with a for loop to access a nested array and retrieve a specific property from an

As someone who is new to JavaScript, I have a question regarding using Mongoose. Why am I encountering an error when trying to access a property with a for loop? The schema I am working with contains embedded schemas. Usr.findOne({numCli: req.body.numTar ...

Tips on setting the appropriate route in Node Express for accessing bower_components?

I am having trouble with correctly defining the path for bower components in my file structure. Here is how it looks: projectName | - client/ | - app/ | - bower_components/ | - node_modules/ (grunt tasks) | - test ...

Unable to prevent git from continuously keeping track of package-lock.json

After updating to npm v5, a new package-lock.json file is generated when running npm install. Although it is advised to commit this file, I am facing an issue where the content of this file differs between my development machine and the server. Even if I ...

Using VueLoaderPlugin() results in an 'undefined error for 'findIndex' function

Currently, I am in the process of integrating a Vue CLI app into another web project that we are actively developing. The Vue app functions without any issues when utilizing the development server bundled with Vue CLI. Due to the presence of .vue files wi ...

Send the context parameter value of Unified Service Desk to a JavaScript web resource in CRM

Currently, I am working on CRM 8.2 and Unified Service Desk 4.1. I have a specific requirement where I need to pass parameter values from within Unified Service Desk Data Parameters to a JavaScript Webresource. I have come across some resources that sugge ...

Attempting to personalize the CSS for a tab within a table in Material design is unsuccessful

Within my Angular 5 application, I have implemented the Material API. One of the components in my project is a table with 2 tabs structured like this: <mat-tab-group> <mat-tab> <mat-table> <!-- content --> </mat- ...

JavaScript salary calculation function not functioning properly

Once the user inputs the employee's name and the number of hours they worked on the HTML form, the submit button captures this information and stores it in variables for calculating their pay. The script also factors in overtime pay. Despite feeling l ...

Use either Jquery or CSS3 to hide a div if one of its inner divs is empty

I have multiple data sets to display in divs with the same class name. Each div contains two inner divs. <div class="div1"> <div class="div2">Abc</div> <div class="div3"><?php echo $row['SOME VALUE']; ?>< ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

Using Javascript or Jquery, you can submit a form without the need for a button

I'm attempting to submit a form without using a button by invoking a JavaScript function and processing the form with JQUERY/PHP. My goal is for the form to be submitted silently on the backend without causing the page to reload. However, I keep encou ...

Is it necessary for the error event of xmlhttprequest to include an error message?

Currently, I am in the process of developing an AJAX request within a Firefox extension. The following code snippet illustrates my approach: function GetMenu(){ var oReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); ...

Receiving a WAV audio file via HTTP POST on a Node/Express server

I am attempting to transfer an audio file named audio.wav using cURL to my Express server. The cURL request I am using is as follows: curl -X POST --data-binary @"audio.wav" -H "Content-Type: audio/wav" localhost:3000/extract_indicators/audio/darksigma ...

Problem encountered while performing npm installation on Ubuntu due to ENOENT error with lstat

I've been working on a project that handles blog posts and recently deployed it on a cloud platform without any issues. However, I decided to clean up my node_modules folder by deleting it and reinstalling using npm install. After doing so, I encount ...

Modifying Image on Tab Click using jQuery

In my current WordPress project, I am working on dynamically changing an image based on the tab that is clicked. I would like to use jQuery's fade effect to smoothly replace the image with a new one that is relative to the specific tab being clicked. ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

import an external JavaScript file in an HTML document

Looking to load a .js file from a simple HTML file? If you have these files in the same folder: start.js var http = require('http'); var fs = require('fs'); http.createServer(function (req, response) { fs.readFile('index.htm ...