Nate
Nate

Reputation: 28354

How to stop user from leaving page after submitting form (i.e. while it's processing)?

There are lots of similar questions on here, but I haven't found any that deal with stopping a user from leaving a page after submitting a form (i.e. while it's processing).

I have a page on my website with a form that takes a long time to submit (sometimes as long as 15 seconds), so I want to have a popup warning to keep the user on the page after they submit the form.

The problem is that no matter how I try using window.onbeforeunload, I always get a confirmation dialog from that function when the form is submitted, which is not what I want. I don't want the user to get the confirmation dialog when the form is submitted, but rather after it's submitted and only if they try to leave the page after that.

HTML:

<form id="myform" method="post" action="" onsubmit="formSubmitted();">
    <button type="submit" onclick="return checkForm();">submit form</button>
</form>

Javascript:

formSubmittedFlag = 0;

function checkForm()
{
    ...

    if(...)
    {
        return true;
    }
    else
    {
        return false;
    }
}


function formSubmitted()
{
    formSubmittedFlag = 1;
}



window.onbeforeunload = function()
{
    if(formSubmittedFlag == 1)
    {
        return "Are you sure you want to leave the page?";
    }
}

Is there a way to accomplish what I'm wanting?

Upvotes: 3

Views: 823

Answers (2)

markasoftware
markasoftware

Reputation: 12652

replace the contents of formSubmitted with this:

sessionStorage.formSubmittedFlag=true;
notReloaded=true;

And replace the contents of window.onbeforeunload with this:

    if(sessionStorage.formSubmittedFlag===true&&notReloaded!=true)
        return 'do you want to leave?';

Upvotes: 1

Barmar
Barmar

Reputation: 780744

Submit the form using AJAX rather than the form's built-in action. The jQuery Form Plugin may be helpful.

Upvotes: 2

Related Questions