Sometimes I don’t really want to pass form elements one by one in my ajax call, I just want to pack them all in one giant obj and send it over to the backend script. After looking for a while, I found the solution. See sample code below.
json_str = JSON.stringify($('#my_form').serializeArray());
$.ajax({
url: 'do_something.php',
type: 'POST',
dataType: 'json',
data: {
form_data: json_str
},
success: function(data) {
// do something with data
},
error: function(request, error) {
alert('error: '+error+'nreadyState: '+request.readyState+'nstatus: '+request.status);
alert('responseText: '+request.responseText);
}
});
Yea, serializeArray() will convert a form object to a javascript array. Notice this method can only apply to form objects. Then the stringify method will convert the array to a json string.
Once the json string gets sent over, here is what happens on the php side. I like associated arrays.
$form_data_encoded = $_POST['form_data'];
$form_data_decoded = json_decode($form_data_encoded);
// building an associated array
$form_data = array();
foreach ($form_data_decoded as $obj){
$name = $obj->{"name"};
$value = $obj->{"value"};
$form_data[$name] = $value;
}
In case you are a pure javascript dude, here is some code to build an associated array in javascript out of that json_str from above.
var arr = jQuery.parseJSON(json_str);
var dict = new Array();
for (k in arr){
arr2 = arr[k];
dict[arr2.name] = arr2.value;
}