function onul() { if (times == 0) { var leave = confirm(your_message); if (!leave) { location = self.location; times++; } else location = url('afile.php?refer=filename.html'); } } in afile.php do your database stuff then redirect to $_REQUEST['refer'], ie <?php header('Location:'.$_REQUEST['refer']);?> Something like that, not sure if my code is exact but play around with it. Not sure how to cancel the onunload event, its possible that if the function just returns false this might do it, but not sure, you'll have to try it...