user34484 user34484 - 1 year ago 44
Javascript Question

send cookie data to server without page load

I am storing users response to questions (multiple choice) in cookie . the server extract the data from cookie only after user has attempted 20 questions .
the problem is when user has attempted only lets say , 10 question and leaves the site . responses in cookie is not available to server .
the requirement doesn't allow me to extract cookie data from every page load .
i was thinking of triggering a page load , before cookie expires time so that , those extra data can be sync up with server . but could'nt find any solution .

appreciate any pointers on this problem

example : there are 500 pages , all are multiple choice question .
when user attempt first question , the answer is recorded in cookie .
second page/ second question /next page load . the server looks at cookie ...does nothing as it has only one record .
the next question ...again user response is saved in cookie . server does nothing until it finds 20 records ( indicator of 20 records is given by a flag flush, if its yes, server extract the cookie data of all 20 records/question and update the database , it then clears cookie and wait again for 20 records before extraction .
now if user solves 10 next question which are recorded in cookie and leaves the site , those extra 10 questions are lost since the server has not extracted them until last page load .

Thanks ,

Answer Source

If you are asking, "How do I trigger an event when a session cookie expires?" I don't think you can, unless the browser exposes a special API to do so. The cookie will expire either when the browser is closed, or at a specific date/time— but your script will stop running when its particular window is closed.

If you don't want to change your server logic, or offer your users an explicit "Save" button, I suggest this:

  1. Add a beforeunload event handler that sends a request to the server with the "flush" flag, indicating that the user is leaving the page and the server should store all remaining data.

  2. Disable that event handler if the user is about to advance to another question page.

How you implement 2. depends on how your application currently triggers the transition between question pages.