Reputation: 7390
Starting Rails web url: /analytics?param1=a¶m2=b
If the user changes calendar dates it triggers a JS function with the new selected dates (start_date and end_date). Then I have to pass them to the controller together with previous params1 and params2 and reload the page.
New web URL: /analytics?param1=a¶m2=b&start_date=YYYY&end_date=YYYY
Note: param1 and param2 could be missing and optional.
I want to use Turbolinks but I am wondering which is the cleanest way to do this.
$('#reportrange').on('apply.daterangepicker', function(ev, picker) {
let startDate = picker.startDate.format('YYYY-MM-DD');
let endDate = picker.endDate.format('YYYY-MM-DD');
Turbolinks.visit(....)
});
Upvotes: 2
Views: 678
Reputation: 1968
Depending on your required level of browser support, you could do this with URLSearchParams
:
$('#reportrange').on('apply.daterangepicker', function(ev, picker) {
const startDate = picker.startDate.format('YYYY-MM-DD');
const endDate = picker.endDate.format('YYYY-MM-DD');
const params = new URLSearchParams(window.location.search)
params.set('start_date', startDate)
params.set('end_date', endDate)
Turbolinks.visit(window.location.pathname + '?' + params.toString())
});
If you don't want to stay on the same path as you currently are (I understood this from your question, so I assume you do want to stay), then you need to change window.location.pathname
to whatever is the target path.
See https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams for documentation.
Upvotes: 2