Organizing outcomes from a for each function into an array using javascript

I have a form with multiple values of the same name, and I need to arrange this data in an array before sending it via AJAX. However, when I try to do this using the .push function, I encounter an error that says "Uncaught TypeError: dArray.push is not a function."

            var g =  document.getElementsByName("dataA[]"); //equals 1, 11, 111

            var dArray = [];
            var eArray = [];
            var fArray = [];
            var gArray = [];
            var hArray = [];
            
    for(var i=0;i<g.length;i++){
            dArray = d[i].value;
            eArray = e[i].value;
            fArray = f[i].value;
            gArray = g[i].value;
            hArray = h[i].value;
            
            dArray.push(d[i].value);  //Desired [1,11,111]
            eArray.push(e[i].value);
            fArray.push(f[i].value);
            gArray.push(g[i].value);
            hArray.push(g[i].value);
            }
            
            var dArrayb = JSON.stringify(dArray);   //Desired ["1","11","111"]
            var eArrayb = JSON.stringify(eArray);
            var fArrayb = JSON.stringify(fArray);
            var gArrayb = JSON.stringify(gArray);
            var hArrayb = JSON.stringify(hArray);

            
            var dataArray = "DataD="+ dArrayb +"&DataE="+ eArrayb +"&DataF="+ fArrayb +"&DataG="+ gArrayb +"&DataH="+ hArrayb +"";
            alert(dataArray);

Desired Results

            var dataArray = "DataD=["1","11","111"]"&DataE=["2","22","222"]"&DataF=["3","33","333"]"&DataG=["4","44","444"]"&DataH=["5","55","55"]"
                    

Ajax send

    $.ajax({
    type: "POST",
    url: "SaveData.php",
    data: dataArray,
    dataType: 'json', 
    async: false,
    crossDomain: true,
    cache: false,
    
    success: function (output){ 
    alert(output);
    } //success response
    
    }); //Close $.ajax  

Answer №1

The reason for the error message is that you are reassigning values to variables inside your loop which were supposed to be of type array. To fix this issue, you need to use different variable names.

dArray = d[i].value;
            eArr = e[i].value;
            fArr = f[i].value;
            gArr = g[i].value;
            hArr = h[i].value;


dArray.push(d[i].value);  //Expected output [1,11,111]
            eArray.push(eArr);
            fArray.push(fArr);
            gArray.push(gArr);
            hArray.push(hArr);

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

Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates? array = [ {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'} ]; The desired output is: result = [{id: ...

The category parameter is missing or empty, triggering ActionController::ParameterMissing error

Upon submitting the form with a simple code via an ajax request, I encountered an error. Below is the code snippet: <%= form_for(@category) do |f| %> <% if @category.errors.any? %> <div id="error_explanation"> <h2><% ...

The Jade variable assignment variable is altered by the Ajax result

Seeking a solution to update a Jade variable assigned with the results of an ajax post in order for the page's Jade loop to utilize the new data without re-rendering the entire page. route.js router.post('/initial', function(req, res) { ...

Downloading Several Files Simultaneously in Chrome

Since the last Chrome update, my website has encountered an issue. The code snippet below, which was designed to download multiple files, is now only opening the last file in the same tab. I have ensured that my Chrome settings still allow for multiple dow ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

When I click on .toggle-menu, I want the data-target to have a toggled class and the other divs to expand

Looking to achieve a functionality where clicking on .toggle-menu will toggle a class on the specified data-target element and expand other divs accordingly. jQuery(document).ready(function() { var windowWidth = jQuery(window).width(); if (win ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...

What is the best way to add elements to an array that has a predetermined fixed size?

I am looking to create a program that involves inserting elements into an array: The initial elements of the array 20 34 45 2 10 Please provide the index and number for insertion 3 12 Elements after insertion 20 34 45 12 2 10 To start, I define an array ...

Trouble with PUT request for updating user password using Express.js with mongoose

I've encountered a puzzling issue while working on my Express.js application. Specifically, I have created an endpoint for updating a user's password. Surprisingly, the endpoint functions flawlessly with a POST request, but fails to work when swi ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Encountering issues with app functionality following update to Ionic RC4 version

Since upgrading from Ionic rc3 to rc4, I've been facing difficulties running my app smoothly. The app compiles without any errors when I use ionic-app-scripts build --prod, but when I try to run it on my iPhone, all I get is a blank screen and an err ...

Running the command Yarn build with Vite.js and React.js is encountering issues and is not functioning properly

Lately, I've been experimenting with Vite in my React projects. However, when I execute the command yarn build, it creates a Build folder but the application fails to work. When I open the index.html file, all I see is a blank page. Interestingly, e ...

"""Exploring the use of query strings with jQuery for Ajax pagination

Here's the issue I'm facing (apologies for any mistakes in my English): I've been using a library called "Jquery_pagination" and the pagination functions perfectly without any issues. However, there is one problem. When a user clicks on a s ...

JavaScript decimal precision function malfunctioning with currency format conversion

My current snippet works perfectly with the currency format 249.00, but I need to adapt it for a site that uses euros with pricing in the format 249,00. When I make this change, the total calculation goes haywire and shows as 29.900,00. Can someone advise ...

What is the best way to retrieve all objects from this data model?

I am looking to collect all the Model Objects from the data structure provided below. const PRODUCTS = [ { brand: 'Audi', allSeries: { serie: 'A3', allModels: [ { model: ' ...

Is a pair of <type, type> or two 'type' variables more memory-efficient?

When comparing the memory usage, which of the following options requires less memory? short X; short Y; pair<short,short> Coords; ...

As the value steadily grows, it continues to rise without interruption

Even though I thought it was a simple issue, I am still struggling to solve it. What I need is for the output value to increment continuously when I click the button. Here is the code snippet I have been working on: $('.submit').on('click&a ...

Clicking to center div elements

When clicking on my div elements, they transform into flipcards and expand to a size of 600px by 600px. I want these divs to be centered in the middle of the screen when clicked, and then move back to their original position when clicked again. I've b ...

Guide: Creating an AngularJS directive for displaying a jQuery dialog that triggers submission on pressing the Enter button

Looking to create a similar functionality to the jQuery modal form Dialog in my AngularJS app to collect the username from the user. I've tried using the twitter-bootstrap modal and AngularUI dialog, but both are lacking in two key areas: Auto-focu ...

Events that are loaded using jQuery

My webpage features dynamic content generated by PHP, and I am looking to utilize jQuery's load function to refresh the div container periodically. This will ensure that new content is displayed on top of the existing content. The jQuery function I a ...