Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincej's avatar
Level 15

laravel save data before closing page

I have some dynamic JS data on the page. When the user goes to a new page I need that data to be automatically saved for use when they return. When they return, the data must be available for increment. So, for example: I have counted 10 students having arrived. I am not doing page refreshes, so I am counting using JS. Great. My user leaves the page, but comes back later. They need to continue adding student to the original 10. Without some auto storage, the original data is lost.

I have tried using localStorage without success. I have also tried using onbeforeunload, but that does not give an autosave capability. This all might sound trivial, but it is deceiving.

Any suggestions? Many thanks !

0 likes
5 replies
rodrigo.pedra's avatar

Reading the first paragraph I already thought: localStorage for the rescue! But then on the second paragraph you say you already tried it.

What went wrong with localStorage? Can you provide the code you used to interact with it?

vincej's avatar
Level 15

Thanks for coming back!

The problem with localStorage is that as the count increments, the local storage value is incrementing as well. That is a good thing ..... UNTILL you come back to the original page. Let me show you:

  var count = 0;

    $("input:checkbox[name=timeIn]").on('click', function () {    // STUDENT ARRIVES 
       count++;   						// THIS COUNTS THE  STUDENTS WHO HAVE ARRIVED. 
         let lastCount =  localStorage.setItem('Count', count);  // STORE THE LAST COUNT, AND THE TEACHER LEAVES PAGE. 
		        
TEACHER COMES BACK, AND CONTINUES TO COUNT - BUT, var count is now reset to 0, and now the "LastCount" is wrong, and not incrementing. 

$("#totalHeadCount").text(lastCount)

Since my original post, I am now thinking that perhaps I should do some kind of "onclick" of the registration href (ie return) which then would call a JS function to count all the students from fresh .... sounds like hassel.

rodrigo.pedra's avatar
Level 56

@vincej thanks!

When this page loads you could hydrate the count variable from localStorage:

var count = Number(localStorage.getItem('Count') || 0);

// ...

Just don't forget to remove or to reset the Count from localStorage when they finish working with the data.

vincej's avatar
Level 15

Thank you !! I knew it was trivial .... but the obvious defeated me! Many Thanks !

1 like

Please or to participate in this conversation.