rwkiii rwkiii - 3 months ago 12
jQuery Question

Send form with associative array via AJAX to PHP

I have a form that contains fields of an associative array:

<label for="my_array[][system]">System</label>
<input id="my_array[][system]" type="text" value="" name="my_array[0][system]">

<label for="my_array[][name]">Name</label>
<input id="my_array[][name]" type="text" value="" name="my_array[0][name]">


I'm trying to get this form posted to PHP using Ajax. I've attempted this:

$.ajax({
type: "POST",
dataType: "json",
url: ajaxurl,
data: {
action: "update_postmeta",
post_id: post_id,
nonce: nonce,
my_array: $('input:text[name="my_array*"]')
.each(function() { values[this.name] = $(this).val() })
},
success: function (response) {
alert(response);
},
error: function ( jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + '\r\n\r\n' + errorThrown);
}
})


The problem is on this line of code:

my_array: $('input:text[name="my_array*"]')
.each(function() { values[this.name] = $(this).val() })


.each() is not a function... I'm not sure how to get
my_array
populated with the form's data in the same structure it would be using a regular form submission (without Ajax).

How do I post a form's data when it is created with an associative array?

Answer

Change your my_array function() to auto-invoke the function and return an array of key: value objects:

{ 
    ...,
    my_array: (function() { 
        var my_array = [];
        $('input:text[name="my_array*"]')
            .each(function() {
                my_obj = {};
                my_obj[this.name] = $(this).val();
                my_array.push(my_obj);
            });
        return my_array;
    })()
}

Also, you may need to use the attributeStartsWith selector syntax:

jQuery( "[attribute^='value']" )

Comments