Converting form fields with varying sets of data into JSON using JavaScript

I am currently working on a form that contains multiple rows with three fields each - a hidden id, code, and exchange.

<form id="form_in_question">
    <table>
        <tr>
            <td>0</td>
            <td>
                <input type="hidden" id="id[]" value="123" />
                <input type="input" id="code[]" value="abc" />
            </td>
            <td>
               <select id="exchange[]">
                   <!-- Options... -->
               <select>
            <td>
        <tr>
        <!-- unlimited rows... -->
    </table>
</form>

My goal is to create an object structure like this:

data: {
    "0": {
            id: "123",
            code: "abc",
            exchange: "2"
         },
    "1": {
            id: "124",
            code: "bcd",
            exchange: "4"
         }
       }

This way, I can easily send the data as a JSON object via AJAX using the following method:

$("#dialogEditor").dialog('option', 'buttons', {'Save' : function() {
/* Define variables */
var data = $("#form_in_question").serializeArray();
    $.ajax({
    url: 'ajax.codes.php',
    dataType: 'json',
    data: {
        action: "update_codes",
    entryId: entry,
    data: data
    },
                                            type: 'POST',
                                            success: function() {
    ui.showMsg("Codes Updated");
}
});

However, when examining the actual JSON data being passed, it does not group the three fields together correctly. It looks like this:

data[0][name]   id[]
data[0][value]  
data[1][name]   code[]
data[1][value]  zxc
data[2][name]   exchange[]
data[2][value]  15
data[3][name]   id[]
data[3][value]  
data[4][name]   code[]
data[4][value]  BVA
data[5][name]   exchange[]
data[5][value]  5

In its raw form, the data appears as follows: action=update_codes&ResortId=12&data%5B0%5D%5Bname%5D=id%5B%5D&data%5B0%5D%5Bvalue%5D=&data%5B1%5D%5Bname%5D=code%5B%5D&data%5B1%5D%5Bvalue%5D=zxc&data%5B2%5D%5Bname%5D=exchange%5B%5D&data%5B2%5D%5Bvalue%5D=15&data%5B3%5D%...I explored a solution I came across on Stack Overflow, but unfortunately, it did not successfully group the fields as intended.

Answer №1

Here is a sample code snippet that should get the job done:

let dataArray = [];
let tableElement = $("table").get()[0];

for (let i=0; i<tableElement.rows.length; i++) {

    let tableRow = tableElement.rows[i];
    let rowDataObject = {};
    let inputDataObject = {};

    inputDataObject["id"] = $("input[id^='id']", $(tableRow.cells[1])).val();
    inputDataObject["code"] = $("input[id^='code']", $(tableRow.cells[1])).val();
    inputDataObject["exchange"] = $("select[id^='exchange']",$(tableRow.cells[2])).val();

    rowDataObject[$(tableRow.cells[0]).text()] = inputDataObject;

    dataArray.push(rowDataObject);
}

console.log(JSON.stringify(dataArray));

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

Tips for Testing an Ajax jQuery Function Within the document.ready Event

I am in the process of developing a script that utilizes $.ajax to make requests for a json api. My goal is to create unit tests that can verify the results received from the ajax request. For instance, I expect the returned JSON object to contain "items" ...

Issue: unhandled exception: Marketplace URI is not valid

It seems like I am the first one in this community to ask a question related to balancedpayments. I recently started working with balancedpayments. Here's what I've done so far: Set up a test marketplace Added a "webhoo ...

Updating inner text content dynamically can be accomplished without relying on the use of the eval() function

I am faced with a situation where I have multiple batches of code structured like this: 1 <div id="backgrounds" class="centery">Backgrounds 2 <div id="bk1" class="attr">Background 1 3 <div class="container"> 4 ...

Sending Laravel validation errors back to an Ajax request

Need help with passing validation errors back to my ajax call in order to stop the page from progressing and show those errors to the user. /* * Creating a new user after completing the initial part of the form. * */ public function createUserAndOrder(R ...

TabContainer - streamline your selection process with inline tabs

I am currently working on a GUI that includes a TabContainer with two tabs, each containing a different datagrid. I initially created the tabcontainer divs and datagrids declaratively in HTML for simplicity, but I am open to changing this approach if it wo ...

Leveraging promises with node.js and couched/nano for asynchronous operations

Currently experimenting with the Q promises library in conjunction with couchDB and Nano. The code below is able to display messages in the console, however, it seems that the database is not being created as expected. var nano = require('nano') ...

Utilize Javascript to interpret a structure that resembles JSON

My data resembles JSON, with columns and names listed: columns: [ { allowNull: false, autoEnterSubType: 0, autoEnterType: 2, creationOrderIndex: 0, dataType: 4, databaseSequenceName: "seq_admintraties_adminratie_id", flag ...

Adjusting the letter spacing of individual characters using HTML and CSS

Is there a way to set letter-spacing for each character with different sizes as the user types in a text box? I attempted to use letter-spacing in CSS, but it changed all characters to the same size. Is there a possible solution for this? Here is the code ...

Dealing with Unwanted Keys When Parsing JSON Objects

Struggling with parsing a list of Objects, for example: After running the code JSON.parse("[{},{},{},{},{}]"); The result is as follows: 0: Object 1: Object 2: Object 3: Object 4: Object 5: Object Expecting an array of 5 objects like this: [Object,Ob ...

The combination of Node.js module.exports and shorthand ternary operators for conditional statements

Can you explain the purpose of this line 'undefined' != typeof User ? User : module.exports and why is everything enclosed within (function(){})? I am having trouble understanding its significance. This code snippet is extracted from a library f ...

Tips on how to engage in a spontaneous audio experience

I am currently developing a Discord bot with the intention of having it play a random mp3 file upon joining a voice channel. case"join": message.delete( {timeout: 5000}) const voiceChannel = message.member.voice.channel ...

Personalize the Jquery datatables GET request parameters for the server by tailoring them to your preferences

I'm using Jquery datatables and would like to customize the GET request it sends to the server when loading a page, instead of the default GET request. Below is the JavaScript section where the request is sent on load: $(document).ready(function() { ...

Unable to modify the selector to "Remove preview files" on click in PHP and JavaScript

During the process of uploading multiple files (using <input type="file" multiple/>) with preview image file and successfully removing the image preview and file data, I encountered a problem. The issue arises when attempting to change the selector ...

Dealing with a cross-domain web method that returns a 204 status code

I have implemented a Webmethod in ASP.NET and am attempting to access it through jQuery AJAX. When I request the Webmethod directly via browser, I receive a JSON response. However, when I make the call using jQuery AJAX, I am seeing "204 no content" in Fir ...

JS | How can we make an element with style=visibility:hidden become visible?

HTML: <div id="msg-text"><p><b id="msg" name="msg" style="visibility:hidden; color:#3399ff;">This is a hidden message</b></p></div> JS: $('#url').on('change keyup paste', function() { $('# ...

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

Guide to successfully implement a POST action using jquery/ajax Colorbox! Check out the demo here

I stumbled upon a colorbox tutorial and attempted to replicate it with a POST action, but unfortunately, it just continues to load. Check out this fiddle The button represents the problematic POST action, while the text link is the original example that ...

Where can I find the previous version of three.js? What is causing the incompatibility between the old and new versions of

Why is my app facing issues with the updated version of three.js? Can I find the previous version of three.js and why isn't the new version compatible? ...

Invoke the URL with a query string and obtain the response from the specified web page

How can I make a button on my user.php page call action.php?name=john&id=10 without refreshing the page? The action.php page needs to process the query string data (name=john & id=10), execute some action, and then send a message back. Here is an ...

Merge MySQL tables using UNION operator and convert the result into a JSON array

Can someone assist me with a MySQL Query for combining multiple tables using UNION and grouping the result by ID, then outputting the result in JSON_ARRAY format? I have looked at this as a reference, but I'm struggling because my query involves the n ...