user3700346
user3700346

Reputation: 33

Jquery - How to stop this script on form submit

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>

Upvotes: 1

Views: 274

Answers (2)

user3700346
user3700346

Reputation: 33

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

Upvotes: 0

cssyphus
cssyphus

Reputation: 40096

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

Upvotes: 1

Related Questions