1

I created this script to alert a user they are leaving the page without completing the form. The script is ignored when the user clicks the submit button. Unfortunately on the site I am working on, a new page is NOT loaded on form submit, just a thank you message appears on same page (hence any links clicked at that point still gives the alert message). So what I hope to do is instead - CANCEL this script on form submit. Any ideas anyone?? (syntax please!) - I only have SCRIPT level access, I cannot directly edit the submit button.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      var action_is_post = false;
      $("form").submit(function () {
        action_is_post = true;
      });

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

2 Answers2

1

One way around it is to change your strategy a bit.

You are assuming that a visitor to the page will always complete the form. However, there is at least one instance when this is not true: after the form has been submitted and the page re-loads this is no longer true (it is now a new visit to the page and the user will not complete the form this time because it has already been done).

Therefore, change your strategy so that you have the message OFF by default, and only turn it on if the user does something like: (a) click on any form field (.focus() event), (b) depart from a form field (.blur() event), (c) change contents of an element (.change() event), etc.

Example:

<script>
    var exit_message = false; //outside of document.ready

    $(document).ready(function(){
        window.onbeforeunload = confirmExit;

        $('.formField').focus(function(){
            exit_message = true;
        });

        $("form").submit(function () {
            exit_message = false;
        });

    }); //END document.ready

    function confirmExit() {
        if (exit_message)
            return 'Are you sure you want to leave this page?';
        }
    }
</script>

For the above example, note that at least one form field (or all, if you wish) should have the class formField. For example:

<input id="first_name" class="formField" type="text" />

Further Ideas (in response to comment):

If you need to remember the state of the last page interaction (for example, user has already submitted the form, and you wish to remember this for every future page interaction), you can use the PHP $_SESSION super-global variable.

$_SESSION is an array variable for which you can create new associative elements. It is special in that (a) it is built-in to PHP, and (b) it will be unique for each visitor to the page.

To use this super-global, you must enable it by placing session_start(); at the very top of your script. Usually, session_start() must appear before anything else, and certainly before any data/headers are output to the page. Like this:

<?php
    session_start();
    //carry on as usual

This instruction must be at the top of every PHP page that will use the $_SESSION variable.

Now, instead of using a global variable (such as $exit_message = 1), you should use a $_SESSION variable. Let's call it "form_submitted":

PHP:

<?php
    session_start();

    //Note: you may have to use == false /or/ === false... Please test/research
    if ( !isset($_SESSION['form_submitted']) ){
        $_SESSION['form_submitted'] = 0;
    }


    if ( $_SESSION['form_submitted'] == 0 ) {
        echo '<input type="hidden" id="stored_state" value="0" />';
    }

jQuery / javascript:

    function confirmExit() {
        if ( $('#stored_state').val() == 0 )
            return 'Are you sure you want to leave this page?';
        }
    }

To explain the above code:

  • If user has never visited the page before, the session var will not exist. In that case, create it and set value to zero. Else, the value will be what it was last set to.

  • PHP variables cannot be accessed from jQuery (unless you use ajax). Therefore, before finishing outputting the page, add a hidden input field that stores the value of the PHP variable. jQuery/javascript can access that hidden field's value and voila! you have the PHP variable's value available to your script.

NOTE THAT: In your form processing, (at the top of the PHP page I believe you mentioned), you should switch the var value. That is, when the form has been submitted:

<?php
    //At the part where you deal with the form submission data:
    $_SESSION['form_submitted'] = 1;

Read more about the $_SESSION variable here:

TiZag on Sessions

DevShed Sessions

Going Deep Inside Sessions

Session variables explained

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • This works great but it doesn't solve the problem of somebody NOT TOUCHING the form and trying to leave the page. How can I add that??? – user3700346 Jun 03 '14 at 19:51
  • Thanks but...unfortuntaly, as I mentioned in the original question, I have only script level access. This is a CMS (blackbaud) and I have no php access (besides that it's an aspx page anyways). Any way I can just focus on the whole form somehow. The first answer is very close, I just need to add ability of the whole form being ignored.... – user3700346 Jun 03 '14 at 20:40
  • Sorry I will clarify: Users should get alert if: No data entered and leaving page OR Some data entered and leaving page. Alert should no longer happen once submit button has been clicked (page simply displays what you entered on form at that point, new page doesn't load on submit, so after clicking submit, user can see what they have submitted, and are free to leave) -- Thanks for your help I really appreciate it! Sooo000stuck on this! – user3700346 Jun 03 '14 at 20:49
  • Re-reading the OP, if you make the initial var value `display the exit message`, and then only turn that off if the submit button is pressed, then users will always be asked to complete the form. How about this then: *in your form processing PHP code*, set a hidden field to note that the form has now been completed. (This field should always exist, but only contain a **` 1 `** if the form was completed). Then the confirm_exit() fn can access that to determine whether to display the prompt. – cssyphus Jun 03 '14 at 20:50
  • Again - sorry to complicate - but no php access, no ftp access - I can add scripts at html level and that's it.... – user3700346 Jun 03 '14 at 20:53
  • Can you kindly give code examples as well. I am new to JQ. Thanks! – user3700346 Jun 03 '14 at 20:54
  • Hmmmm... This isn't going to work so well if you can't edit the form processing code, because that is how/when you would create the hidden input field. You can create a hidden input like this: **``,** and access it as described in the jQuery part of the 2nd section of my answer: **`if ( $('#stored_state').val() == 0 )`** – cssyphus Jun 03 '14 at 21:00
  • Answer #1 is VERY close to what I am looking for. Just doesn't answer the problem of - what if the form isn't clicked on at all? – user3700346 Jun 03 '14 at 21:05
  • I really don't think there is a way to solve this unless you can (in ASP) set a var value when the form data is being processed and the Thank You message outputted to screen. If you can do that, then outputting a hidden form field with a true / 1 value, and reading the result in jQuery, will do the trick. Failing that, I honestly don't think it's poss. – cssyphus Jun 03 '14 at 21:19
  • Ok thanks so much, I think answer #1 will have to suffice. It solves all problems except if the user enters no data at all. If that is the case they probably want to leave anyways! ;-) thanks so much for the help. – user3700346 Jun 03 '14 at 21:33
  • Before I close just to confirm for sure - Regarding the first script on this page (my original question) there is no way to STOP this script once submit has been pressed ONCE? Ex. some kind of STOP function? That would totally solve my problem. – user3700346 Jun 04 '14 at 15:41
  • Only if you can save the state (i.e. whether the form has been submitted or not). The problem is this: once the form submits onto the same page, the page is refreshed. Question: how does the code know whether (a) this is first visit to page, or (b) form was submitted? Answer: the ONLY information from prior to pressing SUBMIT is sent via the form. SO, the ASP processing code gets involved and *it* needs to pass along the information to the js/jQuery code. Without access to the ASP, I cannot see how you can do it. – cssyphus Jun 04 '14 at 18:45
  • thanks gibberish, you are awesome, I learned ALLOT here. Cheers. Closing question. – user3700346 Jun 04 '14 at 18:53
0

Without file access this cannot be done. Tying into the input fields using focus() is the best solution.