"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values.

I am open to alternative methods, but based on my limited knowledge, this is what I have come up with so far.

The challenge lies in managing a large form with nearly 400 fields for mobile data acquisition. Each piece of data should be sent as it's entered for flexibility and edits until final submission. A green dot is displayed to confirm successful storage, utilizing a <span> with an id named after each field (e.g., FormFieldAStatus).

Form snippet:

<input type="text" class="form-textbox validate[required]" id="input_1" name="formFieldA" size="20" onchange="saveData(); readData()" />
<span class="ajax-success" id="formFieldAStatus"></span>

The existing working code:

function readData() {
  new Ajax.Request('AjaxRead.php', {
    method: 'post',
    parameters: $('Worksheet').serialize(true),
    onSuccess: function(transport) {
      var icon = '<img src="images/greendot.png" align="bottom" style="margin-right:5px;">';
      if (transport.responseText) {
        var json=transport.responseText.evalJSON();
        if(json.formFieldA) { 
          var status = $('formFieldAStatus'); 
          status.update(icon); } 
        if(json.formFieldB) { 
          var status = $('formFieldBStatus'); 
          status.update(icon); } 
        if(json.formFieldC) { 
          var status = $('formFieldCStatus'); 
          status.update(icon); } 
      }
    },
    onFailure:function(){ alert('Something went wrong...') }
  });
}   

However, manually checking each field for updates is not feasible with 400 lines of code.

Here's the code that should work but doesn't:

function readData() {
  new Ajax.Request('AjaxRead.php', {
    method: 'post',
    parameters: $('Worksheet').serialize(true),
    onSuccess: function(transport) {
      var icon = '<img src="images/greendot.png" align="bottom" style="margin-right:5px;">';
      if (transport.responseText) {
        var json=transport.responseText.evalJSON();
        for(var key in json) {
          if(!json[key]=='') {
            var statusName=key+'Status';

// Various methods attempted, none successful                

            var status = $(statusName);
            var status = $(window[statusName]);
            var status = $(key+'Status');
            var status = $(window[key+'Status']);
            eval("var status = $('"+key+"Status');");

// Is there a solution among these?

            status.update(icon); }
        }
      }
    },
    onFailure:function(){ alert('Something went wrong...') }
  });
}   

Your insight would be greatly valued. If there is a more efficient approach, I am eager to learn about it.

Thank you.

Additional details:

I added the following for reference:

console.log('statusname: '+statusName);
console.log('status: '+status);
console.log('status Object: '+Object.inspect(status));

The output was:

statusname: fieldNameAStatus 
status: [object HTMLElement] 
status Object: <span id="fieldNameAStatus" class="ajax-success"> 

for each attempted method,

When uncommenting:

status.update(icon); 

The result changed to:

statusname: formIDStatus 
status: null 
status Object: null

Any ideas?

Answer №1

Consider this approach:

var statusName = json[key] + 'Status';

It appears that you are simply retrieving the key rather than the value. Additionally, remember to check json.hasOwnProperty(key) when using a "for in" loop. If you run console.log(!json[key]=='') after the loop, what is the result?

Answer №2

let messageContent = jsonData[key] + 'Alert';

Answer №3

Success! It finally works. After some investigation, I discovered that the issue was caused by a missing span element for one of the form fields. Strangely, the first field encountered happened to be the form itself. While I didn't really need the form name, the JavaScript functionality associated with the form would break without it. Despite my attempts to make my if statement ignore empty fields, I had to keep it in place. But it’s not a major issue.

I wouldn't have been able to solve this puzzle without the helpful console.log clue. It truly saved the day.

Many thanks once again. Below is the final version of the code:

function readData() {
  new Ajax.Request('AjaxRead.php', {
    method: 'post',
    parameters: $('Worksheet').serialize(true),
    onSuccess: function(transport) {
      var icon = '<img src="images/success.png" align="bottom" style="margin-right:5px;">';
      var noicon = '';
      if (transport.responseText) {
        var json=transport.responseText.evalJSON();
        for(var key in json) {
          var statusName=key+'Status';
          var status = $(statusName); 
          if(!json[key]=='') {
            status.update(icon); }
          else {
            status.update(noicon); }
        }
      }
    },
    onFailure:function(){ alert('Something went wrong...') }
  });
}

Here's the HTML snippet that needs updating:

<span class="ajax-success" id="fieldNameAStatus"></span>

Cheers!

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

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

Utilizing dxautocomplete in a dynamic manner

Friends I have implemented dxautocomplete in devextreme mobile dxlist. However, only the first line is being generated. I am looking to customize each line with different data dynamically. Although the same code repeats in the section below, I need guidan ...

Ways to block WebSocket access on a personal computer

Is it possible to protect my server resources from being accessed by other websites, such as example.com, via WebSocket? I want to prevent them from accessing the server using a URL like "ws://47.80.151.189:1234", and utilizing its resources (bandwidth, me ...

"Utilize jQuery to load a file when hovering over a specific

How can I dynamically load an external file using jQuery when a user hovers over a specific div? I attempted to load the file like a CSS file on hover but was unsuccessful. Is it possible to load a CSS file on hover as I've seen in some examples? $(d ...

Creating a React component that allows for pagination using data fetched from a

I have a Spring Boot endpoint that retrieves and lists items from a database: @RequestMapping(method = RequestMethod.GET, value = "/task", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> processTask(@Valid TaskSearchP ...

When attempting to render mathML in a canvas on Safari, the image load callback does not properly trigger, resulting in

I am currently working on rendering mathML into an HTML5 canvas. One suggestion I received was to embed the mathML as an SVG foreign object, render it into an image, and then display the image within the canvas. However, this method works fine in Firefox ...

Utilize Laravel 8 and Vue Js to dynamically showcase retrieved data in input fields

I am facing a challenge with my Laravel 8 registration form using Vue js. Before submitting the form, I need to verify if the referring user exists in the database. If the user is found, I want to dynamically display their full name in an input field upon ...

Is there a solution for passing multiseries data in JSON that works with AnyChart in ReactJS since the standard method is not functioning correctly?

I need help implementing a column chart using AnyChart in react with multi-series data. Below is a sample JSON structure that I am having trouble passing to the chart. const multiSeriesSettings = { width: 800, height: 600, type: "column", ...

Using Material-UI HOC with props传递

One of my custom components is calling another custom component created using withStyles. Here is the code snippet: import {FormControl, InputBase, InputLabel, withStyles} from "@material-ui/core"; import React from "react"; export const CustomInput = wit ...

Why is it that my JQuery sliders appear perfectly fine when viewed locally, but fail to show up when accessed on

I'm facing an issue with two JQuery sliders on my page. The local version works fine, but when I upload it to my web host, only one slider functions correctly. I need both of them to work as intended. Any insights on how to resolve this problem? See ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

I'm running into a "timeout" issue with socket.io and a self-signed SSL connection. Can anyone help me troubleshoot this?

After setting up a nodejs server with HTTPS, everything seems to be working fine when sending GET requests. However, I encountered an error message 'WebSocket was closed before the connection was established' when trying to connect another nodejs ...

Disable the border and background colors in CloudFlare Turnstile

I have implemented the CloudFlare reCaptcha Turnstile and I am looking to modify the widget by removing the border and background color. I believe this customization can be achieved using CSS or Javascript. Thank you for any assistance! ...

Looking for a method to incorporate an onclick function into a column for renderCell within the MUI Datagrid. Any suggestions?

I'm currently developing a react application and utilizing the MUI Datagrid to present some data. I have incorporated a rendercell to insert an edit icon which should trigger a pop-up modal when clicked. Below is the column setup. export const specifi ...

Deliver the Express.js: transmit outcomes post next() invocation

I have a unique app feature that allows users to create their own routes in real-time. I also want to show a custom 404 message if the route is not found, so I added this code to my last middleware: app.use((req, res, next) => { // ...normal logic ...

What is the best way to store data retrieved using a model.find({}) operation?

I am currently attempting to calculate the average value of a collection in my database using Mongoose and Express. The objective is to utilize this calculated value on the "calculator" page when rendering, which is why it is embedded in a post for that sp ...

Encountering a Next.js installation error due to the inability to locate the module fs

Having trouble with the installation of a new Next.js 14 app. I've searched on Google and Stack Overflow but haven't been able to find a solution. I'm stuck at this point. Can anyone offer some assistance? What I have attempted: npx creat ...

Guide on generating virtual nodes from a string containing HTML tags using Vue 3

Investigation I stumbled upon this solution for converting a simple SVG with one path layer into Vue2 vnode list and wanted to adapt it for Vue3. After scouring resources, including the MDN docs, I couldn't find any pre-existing solutions. So, I dec ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...

Achieving both positive and negative styling in AngularJS with ng-class: A guide

I'm currently working on an application that requires indicating red for negative values and blue for positive values in a calculation. <td class="amount debit"> <input type="text" class="form-control" ng-model="vm.model.form.amount_debi ...