Reputation: 891
I’ve got a HTML Form and I want to pass multiple options to an Array in Ajax.
And in the name
attribute I define the nested array like: name="query[taxonomy_01][value]”
First some code and the question is below.
Rendered HTML
<form>
<input type="hidden" name="query[taxonomy_01][value][]" value="term_01" />
<input type="hidden" name="query[taxonomy_01][value][]" value="term_02" />
<input type="hidden" name="query[taxonomy_02][value][]" value="term_01" />
<input type="hidden" name="query[taxonomy_02][value][]" value="term_02" />
<input type="hidden" name="post_type" value="news" />
<input type="hidden" name="date_from" value="today" />
<button type="button" class="button" >Filter content</button>
</form>
This is the Javascript I have so far:
$(".button").click(function () {
var formData = $(this).closest('form').serializeArray();
console.log(formData);
});
This would be the desired array in JS:
formData = array(
[query] => array(
[taxonomy_01] => array(
[value] => array(
’term_1',
’term_2’,
)
)
[taxonomy_02] => array(
[value] => array(
’term_1',
’term_2’,
)
)
),
[post_type] => 'news',
[date_from] => 'today'
)
How do I process the values to the array and combine them?
Thoughts, am I using .serializeArray()
wrong.
Or should I split the value of the name attribute somehow to convert it into an array?
Unlike the desired output the current output is like this:
formData = array(
[query[taxonomy_01][value]] => ’term_1',
[query[taxonomy_01][value]] => ’term_2’,
[query[taxonomy_02][value]] => ’term_1',
[query[taxonomy_02][value]] => ’term_2’,
[post_type] => 'news',
[date_from] => 'today'
)
Upvotes: 0
Views: 247
Reputation: 925
To convert form value to php style array in javascript, we can use a port of php function parse_str
in javascript found here. Jquery does have a api to get form as encoded string .serialize()
A demo using your form https://jsfiddle.net/cp9akow0/
Upvotes: 1