9

I'm trying to create an multidimensional array with JS so that i can post some data with an Ajax call to PHP. It's probably very simple, but my knowledge of JS is very little regarding this specific thing...

Here's an JSFiddle with the code

what i want is some kind of array 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
            }]
        }],
    }]
};

I'm trying to generate the object array with this piece of code:

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);
    });
}

When i output the variable dataRows to the console, i get the following output:

[Object, row_1: Array[1], row_2: Array[1]]
    0: Object
        bewaarnaam: "Bewaar Naam!"
    __proto__: Object
    length: 1
    row_1: Array[1]
        0: Object
            rowName: Array[1]
                0: Object
                    chests: Array[0]
                        chest_1_1: Array[1]
                            0: Object
                                counter: "1"
                                height: "1"
                                __proto__: Object
                                length: 1

And so on... If I log the variable with console.log(JSON.stringify(dataRows)); I get the following output:

[{
    "bewaarnaam": "Bewaar Naam!"
}]

While if i execute the var data =... part ( first code block ) inside the console, and log the data to the console, i get the following output (i logged it again with the `JSON.stringify function for better readability):

{
    "bewaarnaam": "Bewaar Naam!",
    "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
            }]
        }]
    }]
}

If I print_r the POST value in PHP, i get the following output:

Array
(
    [undefined] => 
)

When i debug the Ajax request with Chrome, i can see that the Form Data got 2 undefineds:

Form data
undefined:
undefined:

So if I understand it right, is the object not created properly, and therefore, it isn't properly send with Ajax. And because of that, PHP can't do anything with the post data...

So my question is pretty simple... What am i doing wrong / how do i fix this problem?

1 Answer 1

5

You're mixing arrays and objects. In javascript, if you're using {key:value}, you want an object rather than an array. If you want [value,value,value] it's an array. When you say x=[{}] you're actually creating an object inside an array, but then you're setting properties on the array (arrays are objects too), rather than in the correct object.

What you most likely want is to just use objects everywhere and get rid of all 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;
});

which creates a structure 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"
          },
          "chest_1_3": {
            "counter": "3",
            "height": "3"
          },
          "chest_1_4": {
            "counter": "4",
            "height": "3"
          },
          "chest_1_5": {
            "counter": "5",
            "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"
          },
          "chest_2_3": {
            "counter": "3",
            "height": "6"
          },
          "chest_2_4": {
            "counter": "4",
            "height": "6"
          }
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! As stated before, I've got little knowledge of Js so i didn't knew i was messing up objects and array's. Thanks for pointing that out for me and providing an fix. Have an very nice day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.