rwkiii rwkiii - 9 months ago 31
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:

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).val() })
success: function (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).val() })

.each() is not a function... I'm not sure how to get
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?


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

    my_array: (function() { 
        var my_array = [];
            .each(function() {
                my_obj = {};
                my_obj[] = $(this).val();
        return my_array;

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

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