2

I have a form, and I would like to ask confirmation when the page is closed by the user before submit the values. I already tried the script described in this question but it seems not to work: the userSubmitted value figure like always true, and the pop-up doesn't appear.

The code in my template is:

 <script>
window.onbeforeunload = function() {
if(!userSubmitted)
    return 'Are you sure that you want to leave this page?';};
</script>

the code in my controller is:

$userSubmitted=false;
//...

$form->handleRequest($request);
       if ($form->isValid()) {
        $userSubmitted=true;

//...
return $this->render('DefaultBundle::formupload.html.twig', array(
       'form' => $form->createView(), 'userSubmitted->$userSubmitted
       )); 
//...
Community
  • 1
  • 1

1 Answers1

5
var warn_on_unload = false; //default false 


$('input,textarea,select').on('change', function () { 
  //making true when user types in , or select
    warn_on_unload = true;
});

$(window).bind('beforeunload', function(){
//warns user if not saving form and closing or browsing other page
    if(warn_on_unload)
    {
        return confirm('Leaving this page will cause any unsaved data to be lost.');
    }

});
Anthony Raymond
  • 7,434
  • 6
  • 42
  • 59
Dimag Kharab
  • 4,439
  • 1
  • 24
  • 45
  • It doesn't work. I don't understand. I'm using it in a template rendered with a twig engine. – user3455230 Mar 28 '14 at 10:59
  • Add `return confirm 'Leaving...'` in there (it's in the suggested edits). The confirm keyword is missing. – Zlatko Mar 28 '14 at 12:01
  • @Zlatko without 'confirm' its working fine , for me when I use confirm it doesn't work ! Is that working for you with confirm ? – Dimag Kharab Mar 28 '14 at 12:23
  • 1
    @CodingAnt Pheraps I found the problem, but I don't know how to solve it. Twig uses by default the "output escaping", in order to avoid XSS attacks. But it pheraps nullify also the $ character. Could it be? Infact it take the function only if I put it as window.onbeforeunload, and not with the character $. – user3455230 Mar 28 '14 at 15:55
  • @user3455230 so is your code up and running now mate ? – Dimag Kharab Mar 28 '14 at 15:57
  • @CodingAnt no. Not yet. – user3455230 Mar 28 '14 at 16:04
  • just use return 'Leaving this page will cause any unsaved data to be lost.'; **without confirm** – Dimag Kharab Mar 28 '14 at 16:05