I am using jQuery and jTable. I have a filter for this jTable: it's a large form with different components (checkboxes, jQuery UI DatePickers, Sliders etc). To filter in the table I invoke the load function:
$('#table').jtable('load', {
filter_param_1 : $('#some-form-component').val(),
filter_param_2 : someTransformation($('#some-other-component').val()),
...
});
On the backend side there is a servlet S1 that parses this filtering criteria and returns the correct JSON with jTable rows - this works great.
Now I need to export the table data to CSV, for this reason I have a different backend servlet S2 that I can POST-navigate to. S2 creates the CSV data and tells the browser to download it as a file - still OK.
I want the CSV export to respect the filter. I need to send the same data as jTable sends to S1 to S2, so that I can re-use the filtering logic from S1 in S2.
The way jTable sends this data is by calling $.ajax()
and passing that JSON structure as data
. jQuery handles the conversion from JSON to POST data and performs an AJAX request.
Unfortunately, I cannot do the same for S2 - I need to send the browser to S2 while sending the POST data at the same time - if I just used $.ajax()
, the browser would not navigate to S2.
All of the components are sitting inside of a <form>
, I can just submit this to S2. Unfortunately this way I lose all the transformation logic, I'd like to re-use it.
If I could replicate the way jQuery serializes that JSON to POST data, I could probably build and submit a form on-the-fly, just like here. So how does jQuery do it?
I ended up using this serialization code https://stackoverflow.com/a/17488875/992988 and the server-side logic that handles both this serialized form and whatever comes from a <form>
can be the same.