10

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?

2
  • What does the structure look like? Commented Jul 31, 2012 at 19:18
  • Can you show some code, especially the name of your <form> <input>'s Commented Jul 31, 2012 at 19:22

7 Answers 7

17

Jquery will take multi dimensional arrays directly, no need to serialize.

var data = {
  foo:  123,
  bar:  456,
  rows: [
    {
      column1 : 'hello',
      column2 : 'hola',
      column3 : 'bonjour',
    },
    {
      column1 : 'goodbye',
      column2 : 'hasta luego',
      column3 : 'au revoir',
    },
  ],
  test1:{
    test2: {
      test3:  'baz'
    }
  }
};

_Post Data in your PHP file would look like this

Array
   (
    [foo] => 123
    [bar] => 456
    [rows] => Array
        (
            [0] => Array
                (
                    [column1] => hello
                    [column2] => hola
                    [column3] => bonjour
                )

            [1] => Array
                (
                    [column1] => goodbye
                    [column2] => hasta luego
                    [column3] => au revoir
                )

        )

    [test1] => Array
        (
            [test2] => Array
                (
                    [test3] => baz
                )

        )

    )

Once you define your data multidimensional array, your Ajax could be as simple as

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

If your post array may have fields that you don't know about, you can access your Post array in your php file easily with

$data = file_get_contents('php://input');
$data = json_decode($data, true);
Sign up to request clarification or add additional context in comments.

1 Comment

Um, your example is not using multidimensional arrays. Multidimensional arrays are arrays of arrays (e.g. - [ [ "apples", "oranges" ] , [ "bananas", "pears" ] ] ). However, you're using single dimensional arrays of objects.
2

I did not find any good solution, so i solved this using JSON.stringify(); here is my code

Client side :

var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url        : '/',
         type       : 'POST',                                              
         data       : {'data':JSON.stringify(data)},
         success    : function(){ }
       });

Server Side:

$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))

Comments

1
$.post(url, {"myarray":arrayData}, function(data){/*stuff*/}, 'json');

server side you would access it for example with php

$myArray = $_POST['myarray'][0];
foreach($myArray as $item)
{
   /*logic here for picking apart your array*/
}

Comments

1

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

Comments

0

From the jQuery docs:

For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked.

Check your code for that first. Hard to help further without seeing your code.

Comments

0

Here is my metacode fragment, which works fine for me ...

    var f={};  

    f.text = "SOME DATA";
    f.any_other_field = some_other_value;
    f.items = [];

    $("#droppable .or").each(function(ee){
          var tmp={};
          tmp.id    = $(this).data("cid");
          tmp.name  = $(this).find(".ornazev").text();
          tmp.price = $(this).data("price");
          tmp.currency = $(this).data("currency");
          tmp.ks    = 1;  
          f.items.push(tmp);
    });
    $.ajax({
      type: "POST",
      url: urlsave,
      data: {"f":f},
      dataType: "text",
.....

Comments

0
$.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.

Comments

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.