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"}
]}
]