Hi I'm trying to submit a form using ajax inside Validate's submitHandler, also using the Chosen library which beautifies multiple selects. The following works:
submitHandler: function(form) {
var form = $(this.currentForm);
var data = {
first_name : form.find('#first_name').attr('value'),
last_name : form.find('#last_name').attr('value'),
chosen_people : form.find('#chosen_people').val(),
};
$.ajax({
type : "POST",
url : "formhandler.php",
data : data,
success : function(response) {
console.log(response);
}
});
}
Server response:
array(
['first_name'] => 'John'
['last_name'] => 'Smith'
['chosen_people'] => array(
[0] => 37
[1] => 42
)
)
The problem is that my form is large and changes often and I don't want to have to keep enumerating all of the input and select elements. I want to just say something like:
var inputs = form.find('input').serializeArray();
var selects = form.find('.chzn-select').val();
var data = $.merge(inputs, selects );
...
I've tried every combination of manually typing things like:
for(var select in selects)
selects[select] = {'name' : select, 'value' : selects[select]};
var serializedSelects = {'name' : 'chosen_people', 'value' : selects };
var data = $.merge(inputs, serializedSelects);
But I just can't get the arrays to nest properly so that the server has the correct array structure in its post variables.
The gist of the problem is that although jQuery provides $.serializeArray() for elements, it doesn't provide something like $.paramArray() to take an associative array and convert it to a serialized array. It can only output serialized strings, which are difficult to manipulate further. I don't want to include another ajax framework, so am hopeful there is a straightforward solution.
P.S. I'm using php5 and jQuery 1.8.3. Here's what I've found so far, perhaps I'm just messing up the formatting of the selects array before I try to add it:
jQuery post() with serialize and extra data
How to serialize a JavaScript associative array?
Jquery.SerializeArray how to add more parameters to it?
Thanks!