jquery window.unload triggers post after unload

Posted by index on Stack Overflow See other posts from Stack Overflow or by index
Published on 2012-11-22T04:58:05Z Indexed on 2012/11/22 4:59 UTC
Read the original article Hit count: 170

Filed under:
|
|

I am trying to do a post to server before unloading a page and I followed this and it's working fine. My problem is the $.post on window.unload is triggered after it has unloaded. I tried it with a signout link and checking on my logs, I get the following:

Started GET "/signout" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by SessionsController#destroy as HTML
Redirected to http://localhost:3000/
Completed 302 Found in 1ms


Started GET "/" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by HomeController#index as HTML
  Rendered home/index.html.erb within layouts/application (0.4ms)
  Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 13ms (Views: 12.9ms)


Started POST "/unloading" for 127.0.0.1 at 2012-11-22 00:15:08 +0800
Processing by HomeController#unloading as */*
  Parameters: {"p1"=>"1"}
WARNING: Can't verify CSRF token authenticity
Completed 500 Internal Server Error in 0ms

NoMethodError (undefined method `id' for nil:NilClass):
  app/controllers/home_controller.rb:43:in `unloading'

First part is the signout and then user gets redirected to root then it runs the post ('/unloading').

Is there a way to make the '/unloading' execute first then execute whatever the unload action was?

I have this as my jquery post

$(window).unload ->
  $.ajax {
    async: false,
    beforeSend: (xhr) ->
      xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
    , url: '/unloading'
    , type: 'Post'
    , data: {
      p1: '1'
    }
  }

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery