0

Here is my piece of code :

    $('#addType').on('submit', function(e) {
        $form = $(this);
        var type = [];
        $(this).find('input[type=number]').each(function() {
            type[$(this).attr('id')] = $(this).val();
        });
        console.log(type);
        $.ajax({
            type: 'POST',
            url: '<?php echo $this->url(array(), 'addType');?>',
            data: {type: type},
            success: function() {
                $form.find('input[type=submit]').attr('disabled','disabled');
            }
        });
        e.preventDefault();
    });

As you can see, it builds an javascript array from the inputs in form#addType and send it to a server side script supposed to handle this array. My problem is that no data is passed through $.ajax({}).

UPDATE

It seems that it comes from the values of the array keys that cannot by litteral. If I put an incremented number as key, the array is successfully passed. How come?

1
  • 1
    JavaScript doesn't have associative arrays. Arrays can only have numerical indices. Also, why not just use .serializeArray()? Just pass the form as a jQuery object and you have your data ready to POST. Commented Mar 20, 2014 at 10:16

1 Answer 1

3

Make the type an object, not an array:

var type = { };

You created type as an array (using []). Array is an object, too, so You can add named members to it, which is what You do in Your loop:

type['my-item-id'] = xxx;

But when You add the type variable to the Ajax request, jQuery checks that the variable is an array and so it iterates through the type as trough an array, so it looks for it's "numerical-indexed" items using type.length (which is 0 as You added none):

for (var i = 0; i < type.length; i++)
    ... type[i] ...

When You create type as an Object (using {}), jQuery sees that it should iterate over type as over an object and does it so and "sees" the "named" items:

for (var i in type)
    ... type[i] ...
Sign up to request clarification or add additional context in comments.

5 Comments

It works! So data passed to server with Ajax can't be an array? It has to be an object?
@Steve it can be an array or an object.
I tried to add the explanation in the answer. Feel free to accept it, thanks! :-)
@Steve — No, arrays are fine, but arrays can't have named properties. (Well, they can, but they won't be serialised).
Many thanks for the explanations. Your answer has been accepted.

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.