I have a page tha displays results. The results are loaded into a content div via an ajax request on (document).ready. The results can be filtered using a form. On $(#filter_form).submit() the ajax request is made and the content div is populated with the filtered results.Up to here all is well.
Clicking a result will load the results details in a new page, non ajax load. On clicking the back button we go back to the results page,the form checkboxes are still checked, but the filters are no longer applied to the results. Obviously on document.ready the first, non filtered, ajax request is made and the non filtered results are loaded.
My initial idea was on page ready to check if any of the form elements are checked, and if they were, to submit the form. Problem is I have no idea how to make this work.
My script to load the filtered results is this:
$('#filter_form').submit(function(e){
e.preventDefault();
$.ajax({
url: '<?=base_url().'catalog/show_listings/?';?>'+queryString,
type:'GET',
data: $('form#filter_form').serialize(),
dataType: 'json',
success: function(listings){
$('#result_container').html(listings);
} // End of success function of ajax form
}); // End of ajax call
});
I managed to figure out how to check if any form elements are active :
var validate= false;
$('#requestfilter_from').each(function(){
if($(this).val() != '' || $(this).attr('checked'))
validate = true;
});
I just have no idea how to combine the two. I tried running the ajax request in the second script (dont have that script to post anymore) but it didnt provide any results.
Any suggestions or pointers would be greatly appreciated.
I think the problems boils down to saving the "state" of the filters (keeping track of which ones are checked even if the user leaves the page).
You can easily do this by appending query parameters to the url. For instance, if someone selects a filter checkbox1
, you can append &checkbox1=true
to the url. This way, even when user leaves the page and hits back button, you will have &checkbox1=true
in the url.
Now, you need to modify the initial loading of data to take query parameters into account. So don't load all the data at the start. Instead, parse query parameter, prepare the url based on filters found in the query params and then fire the ajax query which loads initial data.
Here are the steps -
$(document).ready
, parse query parameter, and&checkbox1=true
was found in the url, make sure input[name=checkbox1]
is checked.This comes with a bonus. Now, your users can also pass around the url with selected filters.
PS: Look into jQuery.param.querystring