I am using jQuery to make a search filter menu. This form contains several form elements like checkbox and input box. When a user make some changes to the form and click on a #apply-filters button, the form will be hidden, and its data will be sent to the server backend for processing via $.post().
If the user made changes to the form but closes it without clicking the #apply-filters button, the filter menu div will be hidden, and the next time the user reopens the filter menu, the initial settings will be shown, not the most recent settings that the user made but failed to click on #apply-filters.
Problelm: What is the best way to do this in jQuery?
HTML
<form id="filter-menu">
<input type="checkbox" id="free" name="free" /><label for="free">Free</label>
<input type="checkbox" id="sale" name="sale" /><label for="sale">Sale</label>
<input type="checkbox" id="rooms_1" name="rooms[]" value=1/><label for="rooms_1">1 Room</label>
<input type="checkbox" id="rooms_2" name="rooms[]" value=2 /><label for="rooms_2">2 Rooms</label>
<input type="text" id="price" val="100" />
<button id="apply-filers">Apply Filters</button>
</form>
jQuery
$('#apply-filters').click(function() {
$('#filter-menu').serializeArray(); // Gives an empty array
$.post('api/someplace',
{ free: 1,
sale: 1,
rooms: [1, 2],
price: 100
}, function() {
console.log('yay');
});
});
UPDATE
When I do
JSON.stringify($('filter-form').serializeArray())
I get
[{"name":"rooms[]","value":"1"},{"name":"rooms[]","value":"2"}]"
However I want to send it to server side via $.post() like
{rooms: [1,2]}
This way I will be able to do on the server side (PHP, after processing with the frameworks function)
$rooms = implode(',', $rooms_array) // gives `1,2`
and the MySQL query can be like
SELECT .... WHERE rooms IN (1,2)
Is this possible? What would be a good way to send to the server side? Also, how would I use the output from serializeArray() to feed into $.post()?
Your
serializeArraymethod returns empty array as your form elements have nonameattributes.If you want to reset the form values you can use JavaScript
resetmethod.