rwkiii rwkiii - 1 year ago 78
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?

Answer Source

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']" )

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download