1

I'm trying to figure how to auto submit a form once the user is out of the page. Is there a way?

Code:

<form class="carform" method="get">
 <input type="hidden" name="number_plate" value="{{ car.number_plate }}">
</form>

So when a user clicks a back button or type in another url, the form will automatically submit the form, so it can send the value inside the form and other views can catch the get method.

EDIT: When the user changes the url or clicks the back button on the browser

Aaron
  • 13
  • 3

2 Answers2

1

You can basically use window.onbeforeunload event, but it won't trigger on page refresh.

window.onbeforeunload = closingCode;
function closingCode(){
    document.getElementById("form").submit();
    return null; //<-- this prevents the dialog confirm box
}
0

Try this:

window.addEventListener('beforeunload', async (event) => {
    event.preventDefault();
    event.returnValue = ''; // For chrome

    await submitYourFormFunction();
});

This works well when you refresh page and click back button on the browser.

Yan
  • 854
  • 1
  • 8
  • 15