I’d like to call a method in my controller when a user leaves a page. Ideally I’d also like to pass in a couple of parameters.
This is what I’ve got. Not sure if I’m handing the parameter properly and my leave method is never called.
In ‘show.html.erb’
<script language="javascript">
$(window).bind('beforeunload', function() {
$.get('/leave?foo='+<%= @bar %>, null, null, null)
});
</script>
In ‘routes.rb’
match '/leave' to: 'posts#leave'
In ‘posts_controller.rb’
def leave
puts params[:bar]
end
Note: putting a link_to directly to /leave works fine and replace the jQuery $.get with return true; throws a dialog when the user tries to leave.
I solved this using unobstrusive JS. In one of my Coffeescript files I put:
I’d like to do this without the alert, but unless I return something, GET doesn’t work. Weird, but it’s a separate question.
Thanks for your help, Mark.