Question

I have one page insert.php where the user can make inputs into a form.

I use javascript to inform the user about possible loss of inserted data when the page is closed.

<script language="JavaScript">
    var needToConfirm = true;

    window.onbeforeunload = confirmExit;

    function confirmExit() {
        if ( needToConfirm )
        return "This page is asking you to confirm that you want to leave - data you have entered may not be saved.";
    }
</script>

Then I have a form that contains an element to download ("save") the data inserted.

<form action='insert.php' method='post'>
    ... other input elemets ...
    <input type="submit" name="save" value="Save" onclick="needToConfirm = false;">
</form>

When this save-button is pressed, no data is lost, since the form just reloads itself and refills the form with the $_POST-data. Hence I set the needToConfirm variable to false to not make the user worried.

Furthermore, the $_POST-data is downloaded when reloading the page (insert.php) using:

session_start();
... store $_POST in $_SESSION ...
Header( 'HTTP/1.1 301 Moved Permanently');
Header($'Location: save.php');

Where in save.php I do this:

session_start();
header( 'Content-disposition: attachment; filename=download.dat' );
... echo $_SESSION-data ...

This downloads the inserted data without closing the already loaded insert.php.

The problem is that the javascript needToConfirm-variable stays on false. Hence when I close the page after clicking on download (even if the download was not confirmed by the user) no warning is shown anymore and data may be lost.

Any ideas how to solve this problem are very appreciated.

(I guess the problem is related to the insert.php somehow not fully reloaded due to the loading of the other page...)

Was it helpful?

Solution

you would need to set up a timer and after some timeout, reset the value again to true (you should not have to use bigger then 100ms)

window.setTimeout('needToConfirm=true', 100);

Put that into the onclick so when there is content to show, the page reloads itself, but when there is just the attachment, the timer fires

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top