To be 100% clear, I’m not asking how to use ajax with WordPress… I already know how to do that.
My issue is that I have form elements with array names that aren’t parsing the way I need them to into the $_POST variable. I’m getting the javascript FormData syntax rather than the PHP syntax.
Example…
the HTML…
<form id="registerForm">
<input name="borrower[0][first_name]">
<input name="borrower[0][last_name]">
<input name="borrower[1][first_name]">
<input name="borrower[1][last_name]">
<button>Submit</button>
</form>
the JS…
$('#registerForm').submit(function() {
var data = $(this).serializeArray();
// also tried data = new FormData(document.getElementById('registerForm'));
$.ajax(
url: ...,
dataType: 'json',
data: {
action: 'some_wp_action',
formData: data
},
success: function(response) {
console.log(response);
}
);
})
the PHP…
add_action( 'wp_ajax_some_wp_action', 'some_wp_action' );
add_action( 'wp_ajax_nopriv_some_wp_action', 'some_wp_action' );
function some_wp_action() {
exit(json_encode($_POST['formData']));
}
the output…
[
{"name":"borrower[0][first_name]","value":"John"}
{"name":"borrower[0][last_name]","value":"Doe"}
{"name":"borrower[1][first_name]","value":"Jane"}
{"name":"borrower[0][last_name]","value":"Doe"}
]
I need the output to be an associative array like it would be if you just posted the form data naturally…
[
{"borrower":[
{"first_name":"John","last_name":"Doe"},
{"first_name":"Jane","last_name":"Doe"}
]}
]
OK so I think the answer is here: Convert form data to JavaScript object with jQuery
You’ll want to use the
serializeObject
function. Here’s a simple fiddle.So your js would probably come out looking something like this:
It’s also unclear from the example you posted why you need to explicitly state the
user[0]
location for only one user anyway, so I simplified it for this example as such:this produced the following output: