js onbeforeunload I want to submit the form after page refresh or close, but failed

I want to submit my form data to database when user refresh or close the window. I tried this, but it didn't work. The p demo1 will change to No when refresh or close. But will change to Yes after refresh or close. But the sumbit part is not trigger. I tried this two method, both of them didn't work document.getElementById("all_questions").submit(); $('#save').click(); It can work if I click the submit button, use Django as framework

    window.onbeforeunload = function(e){

<form method = "POST"  name = "answer_question" id="all_questions">
<p id="demo1">Yes</p>
<div class="save-item1"><button class="save-button" type="submit" id="save" name="Complete">Save</button></div>

Answers: 0