1

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?

12
  • 1
    Post it as a JavaScript object Commented Aug 13, 2016 at 1:08
  • Your question isn't entirely clear. $.fn.each() is a function, and it should work to populate an array. Are you saying .each() isn't working, or that you can't post the array as data via $.ajax()? Commented Aug 13, 2016 at 1:39
  • @Nostalg.io I think the problem is in my selector - is the asterisk being used correctly to select the associative array form fields? Since the selector is failing the .each() is invalid, I think? :S Commented Aug 13, 2016 at 1:46
  • 1
    Yeah, you're right. I've been testing it here on an empty JavaScript console with a known good ajaxurl. That one line does break functionality. The odd part is, the "breaking" part runs fine by itself... Commented Aug 13, 2016 at 3:04
  • 1
    Ok. I think there is an error in that too, but first I want you to try this. Use the new jQuery .ajax() API. The function signature places url as the first parameter: jQuery.ajax( url [, settings ] ) Commented Aug 13, 2016 at 3:14

1 Answer 1

1

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

For completeness, here is an example with using an object instead of an array to directly control the key: value pairs for my_array. Also, I'm using the startsWith syntax.

{ 
    ...,
    my_array: (function() { 
        var my_array = {};
        $('input:text[name^="my_array"]')
            .each(function() {
                // Directly sets the key/value data in the POST.
                // You could modify the key names if desired.
                my_array[this.name] = $(this).val();
            });
        return my_array;
    })()
}
Sign up to request clarification or add additional context in comments.

7 Comments

Ok, this is working for me. My POST data for this page, with some test variables came out to: action:update_postmeta post_id:7 nonce:asdfsdf my_array[0][]: my_array[1][q]: my_array[2][author]: Of course... There was no data in the input fields, so they are blank.
@Nostaig.io The Ajax POST succeeds. All of my other form vars are in $_POST, but no my_array is null. No error. I'm going to do some tracing here.
No. The selector isn't returning any results. I know it's right, but there must be something else happening. Still checking.
Your edit resolved the problem! Thank you. I see that the form vars are making it to the server now. Not in the same structure they would be if the form was submitted as usual without Ajax, but I can at least get data now! Thanks.
You could also set my_array to be an object instead of an array, and then you could manually set the key: value pairs sent.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.