How to pass multi-dimensional array with Jquery AJAX post?

Viewed 51102

I've been using Serialize() to pass checkbox form data with Post() for a basket that can hold multiple items of the same category.

When I post them using the submit button it works fine with multiple values being passed and displayed under one category.

However when I used Jquery serialize() it will only show one item per category and only two categories in total. This is an array issue but I cannot work it out.

Is there an alternative JQuery function i should be using to pass a multi-dimensional array?

7 Answers

This worked for me, with jQuery and laravel 8, building (recursively) an object instead of an array:

function getSorted(wrapper) {
    let set = {};
    let children = $(wrapper).children('.list-group');
    let index = 0;

    children.each(function(i, item) {
        $(item).children('.list-group-item').each(function(j, section) {
            index++;
            set[index] = {};
            set[index].id = $(section).data('id');
            set[index].subsections = getSorted($(section));
        });
    });

    return set;
}

Sent it with ajax the usual way:

let orderingSet = getSorted($('#sections')); // recursive function for all sections

$.ajax({
    type: 'POST',
    url: sortUrl,
    dataType: 'json',
    data: {'id': sectionId, 'to_id': parentId, 'orderingSet': orderingSet}
})

And retrieved it from request: $orderingSet = request('orderingSet');

This is how the server response is displayed (only a part of it) for the multidimensional 'array' created above with specific numeric indexes as sections positions after drag & drop:

enter image description here

$.ajax({
    type:   'post',
    cache:  false,
    url:    './ajax.php',
    data:   { arrayData }
});

You must use {} to contain the { arrayData } variable.

then echo $_POST[arrayData]; will yield Array. If not, it will not send array value.

Related