developing a dynamic structure that can store multiple levels of data

I am grappling with the task of creating a multidimensional array in JavaScript to send data via an Ajax call to PHP. My expertise in JS is limited, especially when it comes to this particular task...

I have shared the code on JSFiddle

The desired structure of the array should be like this:

var data = {
    bewaarnaam: 'bewaarnaam!',
    rows: [{
        row_1: [{
            name: 'Row Name 1',
            x: 450,
            y: 250,
            chest1: [{
                counter: 1,
                height: 5
            }],
            chest2: [{
                counter: 2,
                height: 3
            }]
        }],
        row_2: [{
            name: 'Row Name 2',
            x: 650,
            y: 550,
            chest1: [{
                counter: 1,
                height: 8
            }],
            chest2: [{
                counter: 2,
                height: 4
            }]
        }],
    }]
};

This is the JavaScript code snippet I am using to generate the object array:

function saveThis() {
    var bewaarNaam = $("#bewaarplaatsName").val();
    hide_overlay_save_name();
    log("now where going to save everything with the name: " + bewaarNaam);

    var dataRows = [{
        'bewaarnaam': bewaarNaam
    }];
    $(".rows").each(function (i, obj) {
        var row = $(obj);
        var rowName = $(row).attr('name');
        var chests = [];

        $(".cv_chest", row).each(function (i2, obj2) {
            chests[$(obj2).attr('id')] = [{
                'counter': $(obj2).attr('chest_counter'),
                    'height': $(obj2).attr('chest_height')
            }];
        });

        var rowData = [{
            rowName: [{
                'name': $(row).attr('name'),
                    'x': $(row).css('left'),
                    'y': $(row).css('top'),
                    'chests': chests
            }]
        }];

        dataRows[$(row).attr('id')] = rowData;
    });

    log(dataRows);
    log("sending data with ajax...");

    $.ajax({
        type: 'post',
        cache: false,
        url: '{{ url('
        bewaarplaatsen / nieuw ') }}',
        data: dataRows
    }).done(function (msg) {
        log("ajax success");
        log(msg);
    }).fail(function (msg) {
        log("ajax error");
        log(msg);
    });
}

Upon inspecting the variable dataRows, the output looks like this:

[Object, row_1: Array[1], row_2: Array[1]]
    0: Object
        bewaarnaam: "Bewaar Naam!"
    __proto__: Object
    length: 1
    row_1: Array[1]
        0: Object
          ...

Further analysis by executing the code confirms that the object is properly structured as intended:

{
    "bewaarnaam": "Bewaar Naam!",
    "rows": [{
        "row_1": [{...}],
        "row_2": [{...}]
    }]
}

However, when examining the POST value in PHP, it shows just [undefined]. Additionally, the Chrome debug tool reveals two undefineds under Form Data:

Form data
undefined:
undefined:

It appears that the object is not being created correctly, causing issues when sending it via Ajax and rendering the post data unusable in PHP.

Hence, my question boils down to identifying the misstep in my approach and finding a solution to rectify the problem.

Answer №1

You seem to be confused between arrays and objects in JavaScript. When using {key:value}, you are creating an object, while [value,value,value] represents an array. It appears that when you write x=[{}], you are actually placing an object inside an array but then setting properties on the array itself (remember, arrays are also objects). This may not be the correct structure for your data.

To simplify your code, consider using objects exclusively and eliminating the arrays:

http://jsfiddle.net/k5Q3p/1/

var dataRows = {
    'bewaarnaam': bewaarNaam,
    rows:{}
};

$(".rows").each(function (i, obj) {
    var row = $(obj);
    var rowName = $(row).attr('name');
    var chests = {};

    $(".cv_chest", row).each(function (i2, obj2) {
        log("another chest with id: " + $(obj2).attr('id'));
        chests[$(obj2).attr('id')] = {
            'counter': $(obj2).attr('chest_counter'),
                'height': $(obj2).attr('chest_height')
        };
    });

    var rowData = {
        rowName: {
            'name': $(row).attr('name'),
                'x': $(row).css('left'),
                'y': $(row).css('top'),
                'chests': chests
        }
    };

    dataRows.rows[$(row).attr('id')] = rowData;
});

This will result in a structured format like

{
  "bewaarnaam": "Bewaar Naam!",
  "rows": {
    "row_1": {
      "rowName": {
        "name": "Rij 1",
        "x": "30px",
        "y": "120px",
        "chests": {
          "chest_1_1": {
            "counter": "1",
            "height": "3"
          },
          "chest_1_2": {
            "counter": "2",
            "height": "3"
          },
          ...
        }
      }
    },
    "row_2": {
      "rowName": {
        "name": "Rij 2",
        "x": "30px",
        "y": "200px",
        "chests": {
          "chest_2_1": {
            "counter": "1",
            "height": "6"
          },
          "chest_2_2": {
            "counter": "2",
            "height": "6"
          },
          ...
        }
      }
    }
  }
}

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 proper way to include 'rowspan' specific CSS within an HTML table?

I have an HTML table with rowspans in it: table tr, td { border: 1px solid black; } tr:nth-child(1) { background-color: red; } tr:nth-child(2) { background-color: blue; } <table> <tr> <td rowspan=2>Section 1</td> ...

Working with regular expressions on fieldsets in JavaScript jQuery

I'm facing an issue with a JavaScript regexp and I could really use some assistance. Currently, I have an ajax query result saved in a variable (in this case, a regexp) and I am trying to only match the content within the fieldset tag. Here is a sni ...

Show SVG in its ViewBox dimensions

Currently, I am utilizing the img-Tag to showcase SVG images that have been uploaded by users onto my Amazon S3 storage. <img src="http://testbucket.s3.amazonaws.com/mysvg.svg" /> An issue arises once the image is displayed as it does not retain i ...

Is an update panel necessary for the modal popup extender?

Do we need to use the modal popup extender within an update panel? ...

Transmit information to php script using an html document format

Is there a way to load the file table.php with the data that I am trying to pass when the ajax call is made? I have attempted to do this using the jquery.load method, where the second parameter is a data array, but it doesn't seem to be working. Here ...

Transforming text values into ArrayLists in Robot Framework: A step-by-step guide

Can someone help me with converting this value to an ArrayList? ${doc1}= Open Excel Document filename=${OpenExcel} doc_id=doc1 ${view_bicccicmdu}= Read Excel Row row_num=1 max_num=6 sheet_name=UpperTT ${view_bicccicmduCheckLength}= ...

Connect individuals based on specific criteria within a nested array

My MongoDB collection looks something like this: _id: ObjectId("5cb089e459552d8b8cc6a9e4") username: "admin" password: "12345" gender: "male" interestedIn: "female" movie: Array 0: Object id: "Avatar" title: "Avatar" poster: "~" 1: Object ...

When using Jquery, hovering over an element will cause the full title to be

I have created a toggle div that displays an ellipsis (...) when the long title is longer than 30 characters. Now, I want the full text of the long title to appear when hovering over the div. Check out this JS Fiddle for reference. JS $('#popu ...

Serialization of JSON arrays using Jackson in Java

I've encountered a unique scenario where I'm attempting to serialize data using Jackson. Here is an example of the payload: { "key1": [ [ 10, 11 ], [ 12, 13 ] ...

Passing a variable from the server to the client function in Meteor with a delay

When I invoke a server function from the client side, it executes a UNIX command and retrieves the output on the server. However, I face an issue where the result is immediately returned as undefined by Meteor.call because the exec command takes some time ...

Issues with implementing KoGrid within the Durandal JS framework

How do I properly bind a koGrid in my Durandal JS view page? The code provided below is not functioning as expected. View (HTML) <div id="functiontable" class="form-actions"> <div style="height: 200px" data-bind="koGrid: ...

Tips for toggling the display of multiple ion-input fields based on the selected value from an ion-select dropdown

I am working with an ion-select element that contains options from 1 to 10. <ion-label> Select how many input fields</ion-label> <ion-select> <ion-option value="0"> Zero</ion-option> <ion-option value="1"> One</ion- ...

Struggling with incorporating a button into a ReactJS table

I am trying to display a (view) button in the table, but I encountered the following error: Module parse failed: Unexpected token < in JSON at position 165 while parsing near '...2021", "view": <button type="submit...' You m ...

Tips on displaying a div for a brief moment and then concealing it

Is it possible to create a div that will disappear after 10 seconds of the page loading using PHP or JavaScript? Here is an example of the code: <html> <head></head> <body> <div class="LOADING" id="LOADING" name="LOADING">&l ...

What is the method to retrieve the image's value after dropping it onto the droppable area?

I have implemented a drag and drop feature using jQuery, and I am trying to extract the value of an image and insert it into a database. Additionally, I want to update and remove the image value when it is removed from the droppable area. How can I achie ...

What is the process for attaching the stack when initializing and throwing errors separately in JavaScript?

In all the documentation I've read, it consistently advises to both throw and initialize errors on the same line. For example: throw new Error("My error"); But what if you were to first initialize the error and then throw it on separate lines? For ...

Retrieve a specific value from a JavaScript object

Utilizing the npm package app-store-scraper, I am extracting the app IDs of 1000 apps from the App Store. My objective is to retrieve the "id" field from each JavaScript object and save it in a .csv file. How can I accomplish this task? Below is the code ...

Solving the Dilemma of Ordering Table Rows by Value in JavaScript

I am currently working on a table and my goal is to display rows in an orderly manner based on the sum of their columns. Essentially, I want the rows with the highest values to be displayed first, followed by rows with second highest values, and so on. Des ...

When I try to move my object, it seems to have a mind of its own and flies off the canvas instead of staying where

I am in the process of developing a simple game for a class project. Currently, I am working on ensuring that my rectangle stays within the boundaries of the canvas as I move it using a bounce function. However, I am facing difficulties as the rectangle ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...