"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

What is the process for making a local storage item accessible to others on a network?

Can a local storage item be accessed from any computer on the network using the same Google Chrome extension that was previously set up? ...

Implementing a FadeOut effect for the clicked link

When clicking on each link, I want the same link to fadeOut() after clicking on the ok button in the myalert() function. If clicked on cancel, it should not fadeOut(). How can I achieve this using the myalert() function? For example: http://jsfiddle.net/M ...

Failure to Fetch the Uploaded File's Value Using the Parameter

Objective: My aim is to automatically upload the second input named "file2" to the action result using jQuery code that is compatible with the latest versions of Firefox, Chrome, and Internet Explorer. Issue: The problem arises when HttpPostedFileBase ...

Strategies for preventing multi-level inheritance of TypeScript class properties and methods

In my current JavaScript class structure, the DataService is defined as follows: // data.service.ts export class DataService { public url = environment.url; constructor( private uri: string, private httpClient: HttpClient, ) { } ...

Dynamically insert <td> elements into <tr> element using both jQuery and JavaScript

I am facing an issue with adding a new table data (td) element dynamically to the first table row (tr) in my JavaScript code. Here is the original table before adding the new td element: <table> <tbody> <tr> <t ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

What is the reason for index.html requesting the css or js modules as if they were directories when loading?

I am currently developing a server using expressjs: 'use strict'; var express = require('express'); var logger = require('morgan'); var path = require('path'); var bodyParser = require('body-parser'); va ...

Failed to send JSON data to WebMethod

I am encountering difficulties while attempting to send JSON to a WebMethod. I have provided the method I am using below. If there is a more efficient approach, please advise me. My goal is to store the JSON object in a database. JavaScript function TEST ...

Is PHP loaded prior to the `html body`?

I'm facing a unique challenge where I am currently transferring variables from a PHP page to hidden HTML inputs. The values are extracted from these hidden inputs using a JavaScript function that is called in the following manner: <body onload=" ...

When the buffer is sent through the socket in NodeJS, the console responds by stating that it is not recognized as a buffer

I've been exploring the implementation of AES encryption in ECB mode and here is the code snippet I'm working with. function encrypt (key, iv, plaintext) { if(algorithm == 'aes-128-ecb') iv = new Buffer(''); var ciphe ...

When using jQuery, the PHP variable value is not retrieved from the DIV data-id attribute, instead it just displays the variable name

I currently have the following code: <div class= "obutton feature2" data-id=".$bookID."><button>Reserve Book</button></div> <div class="modal-box"></div> Although this button triggers the jQuery script, the modal box ...

Creating a unique navigation route in React

My application has a consistent layout for all routes except one, which will be completely different from the rest. The entire application will include a menu, body, footer, etc. However, the one-off route should be standalone without these elements. How ...

Arranging a list based on the child property in a React component

Within my application, I have an array mapped to a map that generates a div with a data-date attribute as shown below: It's worth noting that the array cannot be sorted here since there are no dates available for comparison, only the element ID cons ...

Switch between Fixed and Relative positions as you scroll

Just a small adjustment is needed to get it working... I need to toggle between fixed and relative positioning. JSFiddle Link $(window).on('scroll', function() { ($(window).scrollTop() > 50) ? ($('.me').addClass('fix ...

Enhance Shipping Options on Your Woocommerce Cart

I am facing a challenge with providing delivery options for three different countries in my e-commerce store. I want the customer to be able to select their country and instantly see the available delivery methods without having to refresh the entire page ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...

What's the best way to update the value of a TextInput field?

Previously, I was updating the text input using local state. Here's an example: state = {name: ''} ... <AddEditFormInputs onChangeText={name => this.setState({ name })} textStateValue ...

Refresh jQuery DataTable with updated search results

I have a function that loads the DataTable once the document is loaded. $(document).ready(function() { var $dataTable = $('#example1').DataTable({ "ajax": 'api/qnams_all.php', "dataType": "json", "bDestroy": true, "s ...

Verify / Decline SweetAlert will be confirmed in both instances

When you click on "Confirm" or "Cancel", they both trigger the function "isConfirm". Interestingly, the "Cancel" button does not close the alert as expected. It appears to be clashing with the SweetAlert triggered in ...